From 408b350a330cbfc8bb85a88bff5cab5fdfff88fe Mon Sep 17 00:00:00 2001 From: Stuart Charlton Date: Sun, 27 Mar 2016 11:28:13 -0700 Subject: [PATCH] Switch to github version of the Google code golang ODBC driver --- Godeps/Godeps.json | 29 +- .../src/code.google.com/p/odbc/README | 4 - .../src/code.google.com/p/odbc/codereview.cfg | 1 - .../src/code.google.com/p/odbc/codereview.py | 3694 ----------------- .../alexbrainman}/odbc/.hgignore | 0 .../alexbrainman}/odbc/AUTHORS | 0 .../alexbrainman}/odbc/CONTRIBUTORS | 1 + .../alexbrainman}/odbc/LICENSE | 0 .../github.com/alexbrainman/odbc/README.md | 3 + .../alexbrainman}/odbc/api/Makefile | 0 .../alexbrainman}/odbc/api/api.go | 0 .../alexbrainman}/odbc/api/api_unix.go | 4 +- .../alexbrainman}/odbc/api/api_windows.go | 0 .../alexbrainman}/odbc/api/api_windows_386.go | 0 .../odbc/api/api_windows_amd64.go | 0 .../alexbrainman}/odbc/api/mksyscall_unix.pl | 4 +- .../alexbrainman}/odbc/api/zapi_unix.go | 4 +- .../alexbrainman}/odbc/api/zapi_windows.go | 0 .../alexbrainman}/odbc/column.go | 3 +- .../alexbrainman}/odbc/conn.go | 35 +- .../alexbrainman}/odbc/driver.go | 3 +- .../alexbrainman}/odbc/error.go | 7 +- .../alexbrainman}/odbc/foxpro_test.go | 6 +- .../alexbrainman}/odbc/handle.go | 3 +- .../alexbrainman}/odbc/mssql_test.go | 417 +- .../alexbrainman}/odbc/odbcstmt.go | 7 +- .../alexbrainman}/odbc/param.go | 3 +- .../alexbrainman}/odbc/result.go | 0 .../alexbrainman}/odbc/rows.go | 3 +- .../alexbrainman}/odbc/stats.go | 3 +- .../alexbrainman}/odbc/stmt.go | 6 +- .../alexbrainman}/odbc/testdata/fldtest.dbf | Bin .../alexbrainman}/odbc/testdata/fldtest.fpt | Bin .../p => github.com/alexbrainman}/odbc/tx.go | 23 +- .../alexbrainman}/odbc/utf16.go | 0 .../src/github.com/onsi/ginkgo/.gitignore | 4 - .../src/github.com/onsi/ginkgo/.travis.yml | 12 - .../src/github.com/onsi/ginkgo/CHANGELOG.md | 123 - .../src/github.com/onsi/ginkgo/LICENSE | 20 - .../src/github.com/onsi/ginkgo/README.md | 115 - .../github.com/onsi/ginkgo/config/config.go | 170 - .../onsi/ginkgo/ginkgo/bootstrap_command.go | 182 - .../onsi/ginkgo/ginkgo/build_command.go | 68 - .../ginkgo/ginkgo/convert/ginkgo_ast_nodes.go | 123 - .../onsi/ginkgo/ginkgo/convert/import.go | 91 - .../ginkgo/ginkgo/convert/package_rewriter.go | 127 - .../onsi/ginkgo/ginkgo/convert/test_finder.go | 56 - .../ginkgo/convert/testfile_rewriter.go | 163 - .../ginkgo/convert/testing_t_rewriter.go | 130 - .../onsi/ginkgo/ginkgo/convert_command.go | 44 - .../onsi/ginkgo/ginkgo/generate_command.go | 164 - .../onsi/ginkgo/ginkgo/help_command.go | 31 - .../interrupthandler/interrupt_handler.go | 52 - .../sigquit_swallower_unix.go | 14 - .../sigquit_swallower_windows.go | 7 - .../src/github.com/onsi/ginkgo/ginkgo/main.go | 291 -- .../onsi/ginkgo/ginkgo/nodot/nodot.go | 194 - .../ginkgo/ginkgo/nodot/nodot_suite_test.go | 91 - .../onsi/ginkgo/ginkgo/nodot/nodot_test.go | 81 - .../onsi/ginkgo/ginkgo/nodot_command.go | 74 - .../onsi/ginkgo/ginkgo/notifications.go | 101 - .../onsi/ginkgo/ginkgo/run_command.go | 192 - .../run_watch_and_build_command_flags.go | 119 - .../onsi/ginkgo/ginkgo/suite_runner.go | 171 - .../ginkgo/ginkgo/testrunner/log_writer.go | 52 - .../ginkgo/ginkgo/testrunner/run_result.go | 27 - .../ginkgo/ginkgo/testrunner/test_runner.go | 393 -- .../ginkgo/ginkgo/testsuite/test_suite.go | 106 - .../ginkgo/testsuite/testsuite_suite_test.go | 13 - .../ginkgo/ginkgo/testsuite/testsuite_test.go | 167 - .../onsi/ginkgo/ginkgo/unfocus_command.go | 36 - .../onsi/ginkgo/ginkgo/version_command.go | 23 - .../onsi/ginkgo/ginkgo/watch/delta.go | 22 - .../onsi/ginkgo/ginkgo/watch/delta_tracker.go | 71 - .../onsi/ginkgo/ginkgo/watch/dependencies.go | 91 - .../onsi/ginkgo/ginkgo/watch/package_hash.go | 103 - .../ginkgo/ginkgo/watch/package_hashes.go | 82 - .../onsi/ginkgo/ginkgo/watch/suite.go | 87 - .../onsi/ginkgo/ginkgo/watch_command.go | 172 - .../src/github.com/onsi/ginkgo/ginkgo_dsl.go | 525 --- .../onsi/ginkgo/integration/convert_test.go | 121 - .../onsi/ginkgo/integration/coverage_test.go | 54 - .../onsi/ginkgo/integration/fail_test.go | 48 - .../onsi/ginkgo/integration/flags_test.go | 176 - .../onsi/ginkgo/integration/integration.go | 1 - .../integration/integration_suite_test.go | 89 - .../onsi/ginkgo/integration/interrupt_test.go | 51 - .../ginkgo/integration/precompiled_test.go | 53 - .../onsi/ginkgo/integration/progress_test.go | 75 - .../onsi/ginkgo/integration/run_test.go | 373 -- .../ginkgo/integration/subcommand_test.go | 364 -- .../ginkgo/integration/suite_setup_test.go | 178 - .../onsi/ginkgo/integration/tags_test.go | 27 - .../integration/test_description_test.go | 25 - .../integration/verbose_and_succinct_test.go | 80 - .../onsi/ginkgo/integration/watch_test.go | 239 -- .../internal/codelocation/code_location.go | 32 - .../codelocation/code_location_suite_test.go | 13 - .../codelocation/code_location_test.go | 79 - .../internal/containernode/container_node.go | 151 - .../container_node_suite_test.go | 13 - .../containernode/container_node_test.go | 212 - .../onsi/ginkgo/internal/failer/failer.go | 79 - .../internal/failer/failer_suite_test.go | 13 - .../ginkgo/internal/failer/failer_test.go | 125 - .../ginkgo/internal/leafnodes/benchmarker.go | 95 - .../ginkgo/internal/leafnodes/interfaces.go | 19 - .../onsi/ginkgo/internal/leafnodes/it_node.go | 46 - .../ginkgo/internal/leafnodes/it_node_test.go | 22 - .../leafnodes/leaf_node_suite_test.go | 13 - .../ginkgo/internal/leafnodes/measure_node.go | 61 - .../internal/leafnodes/measure_node_test.go | 109 - .../onsi/ginkgo/internal/leafnodes/runner.go | 107 - .../ginkgo/internal/leafnodes/setup_nodes.go | 41 - .../internal/leafnodes/setup_nodes_test.go | 40 - .../internal/leafnodes/shared_runner_test.go | 326 -- .../ginkgo/internal/leafnodes/suite_nodes.go | 54 - .../internal/leafnodes/suite_nodes_test.go | 230 - .../synchronized_after_suite_node.go | 89 - .../synchronized_after_suite_node_test.go | 196 - .../synchronized_before_suite_node.go | 182 - .../synchronized_before_suite_node_test.go | 445 -- .../onsi/ginkgo/internal/remote/aggregator.go | 250 -- .../ginkgo/internal/remote/aggregator_test.go | 311 -- .../remote/fake_output_interceptor_test.go | 17 - .../internal/remote/fake_poster_test.go | 33 - .../internal/remote/forwarding_reporter.go | 90 - .../remote/forwarding_reporter_test.go | 180 - .../internal/remote/output_interceptor.go | 10 - .../remote/output_interceptor_unix.go | 52 - .../internal/remote/output_interceptor_win.go | 33 - .../internal/remote/remote_suite_test.go | 13 - .../onsi/ginkgo/internal/remote/server.go | 204 - .../ginkgo/internal/remote/server_test.go | 269 -- .../ginkgo/internal/spec/index_computer.go | 55 - .../internal/spec/index_computer_test.go | 149 - .../onsi/ginkgo/internal/spec/spec.go | 197 - .../ginkgo/internal/spec/spec_suite_test.go | 13 - .../onsi/ginkgo/internal/spec/spec_test.go | 626 --- .../onsi/ginkgo/internal/spec/specs.go | 122 - .../onsi/ginkgo/internal/spec/specs_test.go | 335 -- .../ginkgo/internal/specrunner/random_id.go | 15 - .../ginkgo/internal/specrunner/spec_runner.go | 324 -- .../specrunner/spec_runner_suite_test.go | 13 - .../internal/specrunner/spec_runner_test.go | 623 --- .../onsi/ginkgo/internal/suite/suite.go | 171 - .../ginkgo/internal/suite/suite_suite_test.go | 35 - .../onsi/ginkgo/internal/suite/suite_test.go | 399 -- .../internal/testingtproxy/testing_t_proxy.go | 76 - .../ginkgo/internal/writer/fake_writer.go | 31 - .../onsi/ginkgo/internal/writer/writer.go | 71 - .../internal/writer/writer_suite_test.go | 13 - .../ginkgo/internal/writer/writer_test.go | 75 - .../onsi/ginkgo/reporters/default_reporter.go | 83 - .../ginkgo/reporters/default_reporter_test.go | 397 -- .../onsi/ginkgo/reporters/fake_reporter.go | 59 - .../onsi/ginkgo/reporters/junit_reporter.go | 139 - .../ginkgo/reporters/junit_reporter_test.go | 241 -- .../onsi/ginkgo/reporters/reporter.go | 15 - .../ginkgo/reporters/reporters_suite_test.go | 13 - .../reporters/stenographer/console_logging.go | 64 - .../stenographer/fake_stenographer.go | 138 - .../reporters/stenographer/stenographer.go | 520 --- .../ginkgo/reporters/teamcity_reporter.go | 92 - .../reporters/teamcity_reporter_test.go | 213 - .../onsi/ginkgo/types/code_location.go | 15 - .../onsi/ginkgo/types/synchronization.go | 30 - .../src/github.com/onsi/ginkgo/types/types.go | 139 - .../onsi/ginkgo/types/types_suite_test.go | 13 - .../onsi/ginkgo/types/types_test.go | 81 - .../github.com/onsi/gomega/format/format.go | 276 -- .../onsi/gomega/format/format_suite_test.go | 13 - .../onsi/gomega/format/format_test.go | 449 -- .../github.com/onsi/gomega/gbytes/buffer.go | 229 - .../onsi/gomega/gbytes/buffer_test.go | 158 - .../onsi/gomega/gbytes/gbuffer_suite_test.go | 13 - .../onsi/gomega/gbytes/say_matcher.go | 105 - .../onsi/gomega/gbytes/say_matcher_test.go | 163 - .../src/golang.org/x/sys/windows/asm.s | 8 - .../x/sys/windows/asm_windows_386.s | 13 - .../x/sys/windows/asm_windows_amd64.s | 13 - .../golang.org/x/sys/windows/dll_windows.go | 275 -- .../src/golang.org/x/sys/windows/env_unset.go | 14 - .../golang.org/x/sys/windows/env_windows.go | 25 - .../src/golang.org/x/sys/windows/eventlog.go | 20 - .../golang.org/x/sys/windows/exec_windows.go | 97 - .../src/golang.org/x/sys/windows/race.go | 30 - .../src/golang.org/x/sys/windows/race0.go | 25 - .../x/sys/windows/registry/export_test.go | 11 - .../golang.org/x/sys/windows/registry/key.go | 178 - .../x/sys/windows/registry/registry_test.go | 682 --- .../x/sys/windows/registry/syscall.go | 28 - .../x/sys/windows/registry/value.go | 330 -- .../sys/windows/registry/zsyscall_windows.go | 73 - .../x/sys/windows/security_windows.go | 435 -- .../src/golang.org/x/sys/windows/service.go | 143 - .../src/golang.org/x/sys/windows/str.go | 22 - .../golang.org/x/sys/windows/svc/debug/log.go | 56 - .../x/sys/windows/svc/debug/service.go | 45 - .../src/golang.org/x/sys/windows/svc/event.go | 48 - .../x/sys/windows/svc/eventlog/install.go | 80 - .../x/sys/windows/svc/eventlog/log.go | 70 - .../x/sys/windows/svc/eventlog/log_test.go | 51 - .../x/sys/windows/svc/example/beep.go | 22 - .../x/sys/windows/svc/example/install.go | 92 - .../x/sys/windows/svc/example/main.go | 76 - .../x/sys/windows/svc/example/manage.go | 62 - .../x/sys/windows/svc/example/service.go | 82 - .../src/golang.org/x/sys/windows/svc/go12.c | 24 - .../src/golang.org/x/sys/windows/svc/go12.go | 11 - .../src/golang.org/x/sys/windows/svc/go13.go | 31 - .../x/sys/windows/svc/mgr/config.go | 139 - .../golang.org/x/sys/windows/svc/mgr/mgr.go | 116 - .../x/sys/windows/svc/mgr/mgr_test.go | 147 - .../x/sys/windows/svc/mgr/service.go | 74 - .../golang.org/x/sys/windows/svc/security.go | 62 - .../golang.org/x/sys/windows/svc/service.go | 316 -- .../golang.org/x/sys/windows/svc/svc_test.go | 118 - .../golang.org/x/sys/windows/svc/sys_386.s | 67 - .../golang.org/x/sys/windows/svc/sys_amd64.s | 41 - .../src/golang.org/x/sys/windows/syscall.go | 77 - .../golang.org/x/sys/windows/syscall_test.go | 33 - .../x/sys/windows/syscall_windows.go | 986 ----- .../x/sys/windows/syscall_windows_test.go | 74 - .../x/sys/windows/zsyscall_windows.go | 2177 ---------- .../x/sys/windows/ztypes_windows.go | 1137 ----- .../x/sys/windows/ztypes_windows_386.go | 22 - .../x/sys/windows/ztypes_windows_amd64.go | 22 - README.md | 8 +- provisioner/go_sql_odbc_driver.go | 2 +- 230 files changed, 496 insertions(+), 30746 deletions(-) delete mode 100644 Godeps/_workspace/src/code.google.com/p/odbc/README delete mode 100644 Godeps/_workspace/src/code.google.com/p/odbc/codereview.cfg delete mode 100644 Godeps/_workspace/src/code.google.com/p/odbc/codereview.py rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/.hgignore (100%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/AUTHORS (100%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/CONTRIBUTORS (94%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/LICENSE (100%) create mode 100644 Godeps/_workspace/src/github.com/alexbrainman/odbc/README.md rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/api/Makefile (100%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/api/api.go (100%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/api/api_unix.go (98%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/api/api_windows.go (100%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/api/api_windows_386.go (100%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/api/api_windows_amd64.go (100%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/api/mksyscall_unix.pl (96%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/api/zapi_unix.go (98%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/api/zapi_windows.go (100%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/column.go (99%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/conn.go (64%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/driver.go (98%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/error.go (92%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/foxpro_test.go (97%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/handle.go (96%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/mssql_test.go (80%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/odbcstmt.go (96%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/param.go (99%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/result.go (100%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/rows.go (95%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/stats.go (94%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/stmt.go (95%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/testdata/fldtest.dbf (100%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/testdata/fldtest.fpt (100%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/tx.go (77%) rename Godeps/_workspace/src/{code.google.com/p => github.com/alexbrainman}/odbc/utf16.go (100%) delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/.gitignore delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/.travis.yml delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/CHANGELOG.md delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/LICENSE delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/README.md delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/config/config.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/bootstrap_command.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/build_command.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/ginkgo_ast_nodes.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/import.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/package_rewriter.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/test_finder.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/testfile_rewriter.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/testing_t_rewriter.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert_command.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/generate_command.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/help_command.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/interrupthandler/interrupt_handler.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/interrupthandler/sigquit_swallower_unix.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/interrupthandler/sigquit_swallower_windows.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/main.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot_command.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/notifications.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/run_command.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/run_watch_and_build_command_flags.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/suite_runner.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testrunner/log_writer.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testrunner/run_result.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testrunner/test_runner.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/test_suite.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/unfocus_command.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/version_command.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/delta.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/delta_tracker.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/dependencies.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/package_hash.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/package_hashes.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/suite.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch_command.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo_dsl.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/convert_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/coverage_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/fail_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/flags_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/integration.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/integration_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/interrupt_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/precompiled_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/progress_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/run_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/subcommand_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/suite_setup_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/tags_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/test_description_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/verbose_and_succinct_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/watch_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/interfaces.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/it_node.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/runner.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/aggregator.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/aggregator_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/forwarding_reporter.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/output_interceptor.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/output_interceptor_unix.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/output_interceptor_win.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/server.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/server_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/index_computer.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/index_computer_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/specs.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/specs_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/random_id.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/testingtproxy/testing_t_proxy.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/fake_writer.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/default_reporter.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/default_reporter_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/fake_reporter.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/junit_reporter.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/junit_reporter_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/reporter.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/reporters_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/stenographer/console_logging.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/stenographer/fake_stenographer.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/teamcity_reporter.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/types/code_location.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/types/synchronization.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/types/types.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/format/format.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/format/format_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/format/format_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/gbytes/buffer.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/gbytes/buffer_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/gbytes/gbuffer_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/gbytes/say_matcher.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/gbytes/say_matcher_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/asm.s delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/asm_windows_386.s delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/asm_windows_amd64.s delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/dll_windows.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/env_unset.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/env_windows.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/eventlog.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/exec_windows.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/race.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/race0.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/registry/export_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/registry/key.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/registry/registry_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/registry/syscall.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/registry/value.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/registry/zsyscall_windows.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/security_windows.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/service.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/str.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/debug/log.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/debug/service.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/event.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/eventlog/install.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/eventlog/log.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/eventlog/log_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/beep.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/install.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/main.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/manage.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/service.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/go12.c delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/go12.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/go13.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/config.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/mgr.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/mgr_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/service.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/security.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/service.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/svc_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/sys_386.s delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/svc/sys_amd64.s delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/syscall.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/syscall_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/syscall_windows.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/syscall_windows_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/zsyscall_windows.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/ztypes_windows.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/ztypes_windows_386.go delete mode 100644 Godeps/_workspace/src/golang.org/x/sys/windows/ztypes_windows_amd64.go diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 9ebac25..d56e67b 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -1,14 +1,10 @@ { "ImportPath": "github.com/cloudfoundry-incubator/cf-mssql-broker", - "GoVersion": "go1.4.2", - "Packages": [ - "./..." - ], + "GoVersion": "go1.6", "Deps": [ { - "ImportPath": "code.google.com/p/odbc", - "Comment": "null-45", - "Rev": "6c29f5e00db9ba7212d3f3d6932ad3c417271eb8" + "ImportPath": "github.com/alexbrainman/odbc", + "Rev": "2fd1af78465e39a1d023f985345e91f1d6fedecf" }, { "ImportPath": "github.com/denisenkom/go-mssqldb", @@ -22,21 +18,6 @@ "ImportPath": "github.com/gorilla/mux", "Rev": "94903de8c98a68d8b4483c529b26a5d146e386a2" }, - { - "ImportPath": "github.com/onsi/ginkgo", - "Comment": "v1.2.0-beta-9-gfbb6632", - "Rev": "fbb663242655b700c623e9629d7781db98957501" - }, - { - "ImportPath": "github.com/onsi/gomega/format", - "Comment": "v1.0-33-ge7b2cd9", - "Rev": "e7b2cd96b5633fbc5f0c221159a5c1e85323f770" - }, - { - "ImportPath": "github.com/onsi/gomega/gbytes", - "Comment": "v1.0-33-ge7b2cd9", - "Rev": "e7b2cd96b5633fbc5f0c221159a5c1e85323f770" - }, { "ImportPath": "github.com/pivotal-cf/brokerapi", "Rev": "15b0ee33a737ef05859cfaa916b04a3dff10d66e" @@ -48,10 +29,6 @@ { "ImportPath": "golang.org/x/crypto/md4", "Rev": "4d48e5fa3d62b5e6e71260571bf76c767198ca02" - }, - { - "ImportPath": "golang.org/x/sys/windows", - "Rev": "58e109635f5d754f4b3a8a0172db65a52fcab866" } ] } diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/README b/Godeps/_workspace/src/code.google.com/p/odbc/README deleted file mode 100644 index 815a3ae..0000000 --- a/Godeps/_workspace/src/code.google.com/p/odbc/README +++ /dev/null @@ -1,4 +0,0 @@ -This repository holds odbc driver written in go. - -It implements database driver interface as used by standard database/sql package. -Calls into odbc dll on Windows, and uses cgo everywhere else. diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/codereview.cfg b/Godeps/_workspace/src/code.google.com/p/odbc/codereview.cfg deleted file mode 100644 index 1c6267e..0000000 --- a/Godeps/_workspace/src/code.google.com/p/odbc/codereview.cfg +++ /dev/null @@ -1 +0,0 @@ -defaultcc: brainman diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/codereview.py b/Godeps/_workspace/src/code.google.com/p/odbc/codereview.py deleted file mode 100644 index 0c9b27a..0000000 --- a/Godeps/_workspace/src/code.google.com/p/odbc/codereview.py +++ /dev/null @@ -1,3694 +0,0 @@ -# coding=utf-8 -# (The line above is necessary so that I can use 世界 in the -# *comment* below without Python getting all bent out of shape.) - -# Copyright 2007-2009 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -'''Mercurial interface to codereview.appspot.com. - -To configure, set the following options in -your repository's .hg/hgrc file. - - [extensions] - codereview = /path/to/codereview.py - - [codereview] - server = codereview.appspot.com - -The server should be running Rietveld; see http://code.google.com/p/rietveld/. - -In addition to the new commands, this extension introduces -the file pattern syntax @nnnnnn, where nnnnnn is a change list -number, to mean the files included in that change list, which -must be associated with the current client. - -For example, if change 123456 contains the files x.go and y.go, -"hg diff @123456" is equivalent to"hg diff x.go y.go". -''' - -import sys - -if __name__ == "__main__": - print >>sys.stderr, "This is a Mercurial extension and should not be invoked directly." - sys.exit(2) - -# We require Python 2.6 for the json package. -if sys.version < '2.6': - print >>sys.stderr, "The codereview extension requires Python 2.6 or newer." - print >>sys.stderr, "You are running Python " + sys.version - sys.exit(2) - -import json -import os -import re -import stat -import subprocess -import threading -import time - -from mercurial import commands as hg_commands -from mercurial import util as hg_util - -# bind Plan 9 preferred dotfile location -if os.sys.platform == 'plan9': - try: - import plan9 - n = plan9.bind(os.path.expanduser("~/lib"), os.path.expanduser("~"), plan9.MBEFORE|plan9.MCREATE) - except ImportError: - pass - -defaultcc = None -codereview_disabled = None -real_rollback = None -releaseBranch = None -server = "codereview.appspot.com" -server_url_base = None -testing = None - -####################################################################### -# Normally I would split this into multiple files, but it simplifies -# import path headaches to keep it all in one file. Sorry. -# The different parts of the file are separated by banners like this one. - -####################################################################### -# Helpers - -def RelativePath(path, cwd): - n = len(cwd) - if path.startswith(cwd) and path[n] == '/': - return path[n+1:] - return path - -def Sub(l1, l2): - return [l for l in l1 if l not in l2] - -def Add(l1, l2): - l = l1 + Sub(l2, l1) - l.sort() - return l - -def Intersect(l1, l2): - return [l for l in l1 if l in l2] - -####################################################################### -# RE: UNICODE STRING HANDLING -# -# Python distinguishes between the str (string of bytes) -# and unicode (string of code points) types. Most operations -# work on either one just fine, but some (like regexp matching) -# require unicode, and others (like write) require str. -# -# As befits the language, Python hides the distinction between -# unicode and str by converting between them silently, but -# *only* if all the bytes/code points involved are 7-bit ASCII. -# This means that if you're not careful, your program works -# fine on "hello, world" and fails on "hello, 世界". And of course, -# the obvious way to be careful - use static types - is unavailable. -# So the only way is trial and error to find where to put explicit -# conversions. -# -# Because more functions do implicit conversion to str (string of bytes) -# than do implicit conversion to unicode (string of code points), -# the convention in this module is to represent all text as str, -# converting to unicode only when calling a unicode-only function -# and then converting back to str as soon as possible. - -def typecheck(s, t): - if type(s) != t: - raise hg_util.Abort("type check failed: %s has type %s != %s" % (repr(s), type(s), t)) - -# If we have to pass unicode instead of str, ustr does that conversion clearly. -def ustr(s): - typecheck(s, str) - return s.decode("utf-8") - -# Even with those, Mercurial still sometimes turns unicode into str -# and then tries to use it as ascii. Change Mercurial's default. -def set_mercurial_encoding_to_utf8(): - from mercurial import encoding - encoding.encoding = 'utf-8' - -set_mercurial_encoding_to_utf8() - -# Even with those we still run into problems. -# I tried to do things by the book but could not convince -# Mercurial to let me check in a change with UTF-8 in the -# CL description or author field, no matter how many conversions -# between str and unicode I inserted and despite changing the -# default encoding. I'm tired of this game, so set the default -# encoding for all of Python to 'utf-8', not 'ascii'. -def default_to_utf8(): - import sys - stdout, __stdout__ = sys.stdout, sys.__stdout__ - reload(sys) # site.py deleted setdefaultencoding; get it back - sys.stdout, sys.__stdout__ = stdout, __stdout__ - sys.setdefaultencoding('utf-8') - -default_to_utf8() - -####################################################################### -# Status printer for long-running commands - -global_status = None - -def set_status(s): - if verbosity > 0: - print >>sys.stderr, time.asctime(), s - global global_status - global_status = s - -class StatusThread(threading.Thread): - def __init__(self): - threading.Thread.__init__(self) - def run(self): - # pause a reasonable amount of time before - # starting to display status messages, so that - # most hg commands won't ever see them. - time.sleep(30) - - # now show status every 15 seconds - while True: - time.sleep(15 - time.time() % 15) - s = global_status - if s is None: - continue - if s == "": - s = "(unknown status)" - print >>sys.stderr, time.asctime(), s - -def start_status_thread(): - t = StatusThread() - t.setDaemon(True) # allowed to exit if t is still running - t.start() - -####################################################################### -# Change list parsing. -# -# Change lists are stored in .hg/codereview/cl.nnnnnn -# where nnnnnn is the number assigned by the code review server. -# Most data about a change list is stored on the code review server -# too: the description, reviewer, and cc list are all stored there. -# The only thing in the cl.nnnnnn file is the list of relevant files. -# Also, the existence of the cl.nnnnnn file marks this repository -# as the one where the change list lives. - -emptydiff = """Index: ~rietveld~placeholder~ -=================================================================== -diff --git a/~rietveld~placeholder~ b/~rietveld~placeholder~ -new file mode 100644 -""" - -class CL(object): - def __init__(self, name): - typecheck(name, str) - self.name = name - self.desc = '' - self.files = [] - self.reviewer = [] - self.cc = [] - self.url = '' - self.local = False - self.web = False - self.copied_from = None # None means current user - self.mailed = False - self.private = False - self.lgtm = [] - - def DiskText(self): - cl = self - s = "" - if cl.copied_from: - s += "Author: " + cl.copied_from + "\n\n" - if cl.private: - s += "Private: " + str(self.private) + "\n" - s += "Mailed: " + str(self.mailed) + "\n" - s += "Description:\n" - s += Indent(cl.desc, "\t") - s += "Files:\n" - for f in cl.files: - s += "\t" + f + "\n" - typecheck(s, str) - return s - - def EditorText(self): - cl = self - s = _change_prolog - s += "\n" - if cl.copied_from: - s += "Author: " + cl.copied_from + "\n" - if cl.url != '': - s += 'URL: ' + cl.url + ' # cannot edit\n\n' - if cl.private: - s += "Private: True\n" - s += "Reviewer: " + JoinComma(cl.reviewer) + "\n" - s += "CC: " + JoinComma(cl.cc) + "\n" - s += "\n" - s += "Description:\n" - if cl.desc == '': - s += "\t\n" - else: - s += Indent(cl.desc, "\t") - s += "\n" - if cl.local or cl.name == "new": - s += "Files:\n" - for f in cl.files: - s += "\t" + f + "\n" - s += "\n" - typecheck(s, str) - return s - - def PendingText(self, quick=False): - cl = self - s = cl.name + ":" + "\n" - s += Indent(cl.desc, "\t") - s += "\n" - if cl.copied_from: - s += "\tAuthor: " + cl.copied_from + "\n" - if not quick: - s += "\tReviewer: " + JoinComma(cl.reviewer) + "\n" - for (who, line, _) in cl.lgtm: - s += "\t\t" + who + ": " + line + "\n" - s += "\tCC: " + JoinComma(cl.cc) + "\n" - s += "\tFiles:\n" - for f in cl.files: - s += "\t\t" + f + "\n" - typecheck(s, str) - return s - - def Flush(self, ui, repo): - if self.name == "new": - self.Upload(ui, repo, gofmt_just_warn=True, creating=True) - dir = CodeReviewDir(ui, repo) - path = dir + '/cl.' + self.name - f = open(path+'!', "w") - f.write(self.DiskText()) - f.close() - if sys.platform == "win32" and os.path.isfile(path): - os.remove(path) - os.rename(path+'!', path) - if self.web and not self.copied_from: - EditDesc(self.name, desc=self.desc, - reviewers=JoinComma(self.reviewer), cc=JoinComma(self.cc), - private=self.private) - - def Delete(self, ui, repo): - dir = CodeReviewDir(ui, repo) - os.unlink(dir + "/cl." + self.name) - - def Subject(self, ui, repo): - s = line1(self.desc) - if len(s) > 60: - s = s[0:55] + "..." - if self.name != "new": - s = "code review %s: %s" % (self.name, s) - typecheck(s, str) - return branch_prefix(ui, repo) + s - - def Upload(self, ui, repo, send_mail=False, gofmt=True, gofmt_just_warn=False, creating=False, quiet=False): - if not self.files and not creating: - ui.warn("no files in change list\n") - if ui.configbool("codereview", "force_gofmt", True) and gofmt: - CheckFormat(ui, repo, self.files, just_warn=gofmt_just_warn) - set_status("uploading CL metadata + diffs") - os.chdir(repo.root) - - form_fields = [ - ("content_upload", "1"), - ("reviewers", JoinComma(self.reviewer)), - ("cc", JoinComma(self.cc)), - ("description", self.desc), - ("base_hashes", ""), - ] - - if self.name != "new": - form_fields.append(("issue", self.name)) - vcs = None - # We do not include files when creating the issue, - # because we want the patch sets to record the repository - # and base revision they are diffs against. We use the patch - # set message for that purpose, but there is no message with - # the first patch set. Instead the message gets used as the - # new CL's overall subject. So omit the diffs when creating - # and then we'll run an immediate upload. - # This has the effect that every CL begins with an empty "Patch set 1". - if self.files and not creating: - vcs = MercurialVCS(upload_options, ui, repo) - data = vcs.GenerateDiff(self.files) - files = vcs.GetBaseFiles(data) - if len(data) > MAX_UPLOAD_SIZE: - uploaded_diff_file = [] - form_fields.append(("separate_patches", "1")) - else: - uploaded_diff_file = [("data", "data.diff", data)] - else: - uploaded_diff_file = [("data", "data.diff", emptydiff)] - - if vcs and self.name != "new": - form_fields.append(("subject", "diff -r " + vcs.base_rev + " " + ui.expandpath("default"))) - else: - # First upload sets the subject for the CL itself. - form_fields.append(("subject", self.Subject(ui, repo))) - - ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file) - response_body = MySend("/upload", body, content_type=ctype) - patchset = None - msg = response_body - lines = msg.splitlines() - if len(lines) >= 2: - msg = lines[0] - patchset = lines[1].strip() - patches = [x.split(" ", 1) for x in lines[2:]] - else: - print >>sys.stderr, "Server says there is nothing to upload (probably wrong):\n" + msg - if response_body.startswith("Issue updated.") and quiet: - pass - else: - ui.status(msg + "\n") - set_status("uploaded CL metadata + diffs") - if not response_body.startswith("Issue created.") and not response_body.startswith("Issue updated."): - raise hg_util.Abort("failed to update issue: " + response_body) - issue = msg[msg.rfind("/")+1:] - self.name = issue - if not self.url: - self.url = server_url_base + self.name - if not uploaded_diff_file: - set_status("uploading patches") - patches = UploadSeparatePatches(issue, rpc, patchset, data, upload_options) - if vcs: - set_status("uploading base files") - vcs.UploadBaseFiles(issue, rpc, patches, patchset, upload_options, files) - if patchset != "1": - MySend("/" + issue + "/upload_complete/" + patchset, payload="") - if send_mail: - set_status("sending mail") - MySend("/" + issue + "/mail", payload="") - self.web = True - set_status("flushing changes to disk") - self.Flush(ui, repo) - return - - def Mail(self, ui, repo): - pmsg = "Hello " + JoinComma(self.reviewer) - if self.cc: - pmsg += " (cc: %s)" % (', '.join(self.cc),) - pmsg += ",\n" - pmsg += "\n" - repourl = ui.expandpath("default") - if not self.mailed: - pmsg += "I'd like you to review this change to" - branch = repo[None].branch() - if branch.startswith("dev."): - pmsg += " the " + branch + " branch of" - pmsg += "\n" + repourl + "\n" - else: - pmsg += "Please take another look.\n" - typecheck(pmsg, str) - PostMessage(ui, self.name, pmsg, subject=self.Subject(ui, repo)) - self.mailed = True - self.Flush(ui, repo) - -def GoodCLName(name): - typecheck(name, str) - return re.match("^[0-9]+$", name) - -def ParseCL(text, name): - typecheck(text, str) - typecheck(name, str) - sname = None - lineno = 0 - sections = { - 'Author': '', - 'Description': '', - 'Files': '', - 'URL': '', - 'Reviewer': '', - 'CC': '', - 'Mailed': '', - 'Private': '', - } - for line in text.split('\n'): - lineno += 1 - line = line.rstrip() - if line != '' and line[0] == '#': - continue - if line == '' or line[0] == ' ' or line[0] == '\t': - if sname == None and line != '': - return None, lineno, 'text outside section' - if sname != None: - sections[sname] += line + '\n' - continue - p = line.find(':') - if p >= 0: - s, val = line[:p].strip(), line[p+1:].strip() - if s in sections: - sname = s - if val != '': - sections[sname] += val + '\n' - continue - return None, lineno, 'malformed section header' - - for k in sections: - sections[k] = StripCommon(sections[k]).rstrip() - - cl = CL(name) - if sections['Author']: - cl.copied_from = sections['Author'] - cl.desc = sections['Description'] - for line in sections['Files'].split('\n'): - i = line.find('#') - if i >= 0: - line = line[0:i].rstrip() - line = line.strip() - if line == '': - continue - cl.files.append(line) - cl.reviewer = SplitCommaSpace(sections['Reviewer']) - cl.cc = SplitCommaSpace(sections['CC']) - cl.url = sections['URL'] - if sections['Mailed'] != 'False': - # Odd default, but avoids spurious mailings when - # reading old CLs that do not have a Mailed: line. - # CLs created with this update will always have - # Mailed: False on disk. - cl.mailed = True - if sections['Private'] in ('True', 'true', 'Yes', 'yes'): - cl.private = True - if cl.desc == '': - cl.desc = '' - return cl, 0, '' - -def SplitCommaSpace(s): - typecheck(s, str) - s = s.strip() - if s == "": - return [] - return re.split(", *", s) - -def CutDomain(s): - typecheck(s, str) - i = s.find('@') - if i >= 0: - s = s[0:i] - return s - -def JoinComma(l): - seen = {} - uniq = [] - for s in l: - typecheck(s, str) - if s not in seen: - seen[s] = True - uniq.append(s) - - return ", ".join(uniq) - -def ExceptionDetail(): - s = str(sys.exc_info()[0]) - if s.startswith(""): - s = s[7:-2] - elif s.startswith(""): - s = s[8:-2] - arg = str(sys.exc_info()[1]) - if len(arg) > 0: - s += ": " + arg - return s - -def IsLocalCL(ui, repo, name): - return GoodCLName(name) and os.access(CodeReviewDir(ui, repo) + "/cl." + name, 0) - -# Load CL from disk and/or the web. -def LoadCL(ui, repo, name, web=True): - typecheck(name, str) - set_status("loading CL " + name) - if not GoodCLName(name): - return None, "invalid CL name" - dir = CodeReviewDir(ui, repo) - path = dir + "cl." + name - if os.access(path, 0): - ff = open(path) - text = ff.read() - ff.close() - cl, lineno, err = ParseCL(text, name) - if err != "": - return None, "malformed CL data: "+err - cl.local = True - else: - cl = CL(name) - if web: - set_status("getting issue metadata from web") - d = JSONGet(ui, "/api/" + name + "?messages=true") - set_status(None) - if d is None: - return None, "cannot load CL %s from server" % (name,) - if 'owner_email' not in d or 'issue' not in d or str(d['issue']) != name: - return None, "malformed response loading CL data from code review server" - cl.dict = d - cl.reviewer = d.get('reviewers', []) - cl.cc = d.get('cc', []) - if cl.local and cl.copied_from and cl.desc: - # local copy of CL written by someone else - # and we saved a description. use that one, - # so that committers can edit the description - # before doing hg submit. - pass - else: - cl.desc = d.get('description', "") - cl.url = server_url_base + name - cl.web = True - cl.private = d.get('private', False) != False - cl.lgtm = [] - for m in d.get('messages', []): - if m.get('approval', False) == True or m.get('disapproval', False) == True: - who = re.sub('@.*', '', m.get('sender', '')) - text = re.sub("\n(.|\n)*", '', m.get('text', '')) - cl.lgtm.append((who, text, m.get('approval', False))) - - set_status("loaded CL " + name) - return cl, '' - -class LoadCLThread(threading.Thread): - def __init__(self, ui, repo, dir, f, web): - threading.Thread.__init__(self) - self.ui = ui - self.repo = repo - self.dir = dir - self.f = f - self.web = web - self.cl = None - def run(self): - cl, err = LoadCL(self.ui, self.repo, self.f[3:], web=self.web) - if err != '': - self.ui.warn("loading "+self.dir+self.f+": " + err + "\n") - return - self.cl = cl - -# Load all the CLs from this repository. -def LoadAllCL(ui, repo, web=True): - dir = CodeReviewDir(ui, repo) - m = {} - files = [f for f in os.listdir(dir) if f.startswith('cl.')] - if not files: - return m - active = [] - first = True - for f in files: - t = LoadCLThread(ui, repo, dir, f, web) - t.start() - if web and first: - # first request: wait in case it needs to authenticate - # otherwise we get lots of user/password prompts - # running in parallel. - t.join() - if t.cl: - m[t.cl.name] = t.cl - first = False - else: - active.append(t) - for t in active: - t.join() - if t.cl: - m[t.cl.name] = t.cl - return m - -# Find repository root. On error, ui.warn and return None -def RepoDir(ui, repo): - url = repo.url(); - if not url.startswith('file:'): - ui.warn("repository %s is not in local file system\n" % (url,)) - return None - url = url[5:] - if url.endswith('/'): - url = url[:-1] - typecheck(url, str) - return url - -# Find (or make) code review directory. On error, ui.warn and return None -def CodeReviewDir(ui, repo): - dir = RepoDir(ui, repo) - if dir == None: - return None - dir += '/.hg/codereview/' - if not os.path.isdir(dir): - try: - os.mkdir(dir, 0700) - except: - ui.warn('cannot mkdir %s: %s\n' % (dir, ExceptionDetail())) - return None - typecheck(dir, str) - return dir - -# Turn leading tabs into spaces, so that the common white space -# prefix doesn't get confused when people's editors write out -# some lines with spaces, some with tabs. Only a heuristic -# (some editors don't use 8 spaces either) but a useful one. -def TabsToSpaces(line): - i = 0 - while i < len(line) and line[i] == '\t': - i += 1 - return ' '*(8*i) + line[i:] - -# Strip maximal common leading white space prefix from text -def StripCommon(text): - typecheck(text, str) - ws = None - for line in text.split('\n'): - line = line.rstrip() - if line == '': - continue - line = TabsToSpaces(line) - white = line[:len(line)-len(line.lstrip())] - if ws == None: - ws = white - else: - common = '' - for i in range(min(len(white), len(ws))+1): - if white[0:i] == ws[0:i]: - common = white[0:i] - ws = common - if ws == '': - break - if ws == None: - return text - t = '' - for line in text.split('\n'): - line = line.rstrip() - line = TabsToSpaces(line) - if line.startswith(ws): - line = line[len(ws):] - if line == '' and t == '': - continue - t += line + '\n' - while len(t) >= 2 and t[-2:] == '\n\n': - t = t[:-1] - typecheck(t, str) - return t - -# Indent text with indent. -def Indent(text, indent): - typecheck(text, str) - typecheck(indent, str) - t = '' - for line in text.split('\n'): - t += indent + line + '\n' - typecheck(t, str) - return t - -# Return the first line of l -def line1(text): - typecheck(text, str) - return text.split('\n')[0] - -_change_prolog = """# Change list. -# Lines beginning with # are ignored. -# Multi-line values should be indented. -""" - -desc_re = '^(.+: |(tag )?(release|weekly)\.|fix build|undo CL)' - -desc_msg = '''Your CL description appears not to use the standard form. - -The first line of your change description is conventionally a -one-line summary of the change, prefixed by the primary affected package, -and is used as the subject for code review mail; the rest of the description -elaborates. - -Examples: - - encoding/rot13: new package - - math: add IsInf, IsNaN - - net: fix cname in LookupHost - - unicode: update to Unicode 5.0.2 - -''' - -def promptyesno(ui, msg): - if hgversion >= "2.7": - return ui.promptchoice(msg + " $$ &yes $$ &no", 0) == 0 - else: - return ui.promptchoice(msg, ["&yes", "&no"], 0) == 0 - -def promptremove(ui, repo, f): - if promptyesno(ui, "hg remove %s (y/n)?" % (f,)): - if hg_commands.remove(ui, repo, 'path:'+f) != 0: - ui.warn("error removing %s" % (f,)) - -def promptadd(ui, repo, f): - if promptyesno(ui, "hg add %s (y/n)?" % (f,)): - if hg_commands.add(ui, repo, 'path:'+f) != 0: - ui.warn("error adding %s" % (f,)) - -def EditCL(ui, repo, cl): - set_status(None) # do not show status - s = cl.EditorText() - while True: - s = ui.edit(s, ui.username()) - - # We can't trust Mercurial + Python not to die before making the change, - # so, by popular demand, just scribble the most recent CL edit into - # $(hg root)/last-change so that if Mercurial does die, people - # can look there for their work. - try: - f = open(repo.root+"/last-change", "w") - f.write(s) - f.close() - except: - pass - - clx, line, err = ParseCL(s, cl.name) - if err != '': - if not promptyesno(ui, "error parsing change list: line %d: %s\nre-edit (y/n)?" % (line, err)): - return "change list not modified" - continue - - # Check description. - if clx.desc == '': - if promptyesno(ui, "change list should have a description\nre-edit (y/n)?"): - continue - elif re.search('', clx.desc): - if promptyesno(ui, "change list description omits reason for undo\nre-edit (y/n)?"): - continue - elif not re.match(desc_re, clx.desc.split('\n')[0]): - if promptyesno(ui, desc_msg + "re-edit (y/n)?"): - continue - - # Check file list for files that need to be hg added or hg removed - # or simply aren't understood. - pats = ['path:'+f for f in clx.files] - changed = hg_matchPattern(ui, repo, *pats, modified=True, added=True, removed=True) - deleted = hg_matchPattern(ui, repo, *pats, deleted=True) - unknown = hg_matchPattern(ui, repo, *pats, unknown=True) - ignored = hg_matchPattern(ui, repo, *pats, ignored=True) - clean = hg_matchPattern(ui, repo, *pats, clean=True) - files = [] - for f in clx.files: - if f in changed: - files.append(f) - continue - if f in deleted: - promptremove(ui, repo, f) - files.append(f) - continue - if f in unknown: - promptadd(ui, repo, f) - files.append(f) - continue - if f in ignored: - ui.warn("error: %s is excluded by .hgignore; omitting\n" % (f,)) - continue - if f in clean: - ui.warn("warning: %s is listed in the CL but unchanged\n" % (f,)) - files.append(f) - continue - p = repo.root + '/' + f - if os.path.isfile(p): - ui.warn("warning: %s is a file but not known to hg\n" % (f,)) - files.append(f) - continue - if os.path.isdir(p): - ui.warn("error: %s is a directory, not a file; omitting\n" % (f,)) - continue - ui.warn("error: %s does not exist; omitting\n" % (f,)) - clx.files = files - - cl.desc = clx.desc - cl.reviewer = clx.reviewer - cl.cc = clx.cc - cl.files = clx.files - cl.private = clx.private - break - return "" - -# For use by submit, etc. (NOT by change) -# Get change list number or list of files from command line. -# If files are given, make a new change list. -def CommandLineCL(ui, repo, pats, opts, op="verb", defaultcc=None): - if len(pats) > 0 and GoodCLName(pats[0]): - if len(pats) != 1: - return None, "cannot specify change number and file names" - if opts.get('message'): - return None, "cannot use -m with existing CL" - cl, err = LoadCL(ui, repo, pats[0], web=True) - if err != "": - return None, err - else: - cl = CL("new") - cl.local = True - cl.files = ChangedFiles(ui, repo, pats, taken=Taken(ui, repo)) - if not cl.files: - return None, "no files changed (use hg %s to use existing CL)" % op - if opts.get('reviewer'): - cl.reviewer = Add(cl.reviewer, SplitCommaSpace(opts.get('reviewer'))) - if opts.get('cc'): - cl.cc = Add(cl.cc, SplitCommaSpace(opts.get('cc'))) - if defaultcc and not cl.private: - cl.cc = Add(cl.cc, defaultcc) - if cl.name == "new": - if opts.get('message'): - cl.desc = opts.get('message') - else: - err = EditCL(ui, repo, cl) - if err != '': - return None, err - return cl, "" - -####################################################################### -# Change list file management - -# Return list of changed files in repository that match pats. -# The patterns came from the command line, so we warn -# if they have no effect or cannot be understood. -def ChangedFiles(ui, repo, pats, taken=None): - taken = taken or {} - # Run each pattern separately so that we can warn about - # patterns that didn't do anything useful. - for p in pats: - for f in hg_matchPattern(ui, repo, p, unknown=True): - promptadd(ui, repo, f) - for f in hg_matchPattern(ui, repo, p, removed=True): - promptremove(ui, repo, f) - files = hg_matchPattern(ui, repo, p, modified=True, added=True, removed=True) - for f in files: - if f in taken: - ui.warn("warning: %s already in CL %s\n" % (f, taken[f].name)) - if not files: - ui.warn("warning: %s did not match any modified files\n" % (p,)) - - # Again, all at once (eliminates duplicates) - l = hg_matchPattern(ui, repo, *pats, modified=True, added=True, removed=True) - l.sort() - if taken: - l = Sub(l, taken.keys()) - return l - -# Return list of changed files in repository that match pats and still exist. -def ChangedExistingFiles(ui, repo, pats, opts): - l = hg_matchPattern(ui, repo, *pats, modified=True, added=True) - l.sort() - return l - -# Return list of files claimed by existing CLs -def Taken(ui, repo): - all = LoadAllCL(ui, repo, web=False) - taken = {} - for _, cl in all.items(): - for f in cl.files: - taken[f] = cl - return taken - -# Return list of changed files that are not claimed by other CLs -def DefaultFiles(ui, repo, pats): - return ChangedFiles(ui, repo, pats, taken=Taken(ui, repo)) - -####################################################################### -# File format checking. - -def CheckFormat(ui, repo, files, just_warn=False): - set_status("running gofmt") - CheckGofmt(ui, repo, files, just_warn) - CheckTabfmt(ui, repo, files, just_warn) - -# Check that gofmt run on the list of files does not change them -def CheckGofmt(ui, repo, files, just_warn): - files = gofmt_required(files) - if not files: - return - cwd = os.getcwd() - files = [RelativePath(repo.root + '/' + f, cwd) for f in files] - files = [f for f in files if os.access(f, 0)] - if not files: - return - try: - cmd = subprocess.Popen(["gofmt", "-l"] + files, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=sys.platform != "win32") - cmd.stdin.close() - except: - raise hg_util.Abort("gofmt: " + ExceptionDetail()) - data = cmd.stdout.read() - errors = cmd.stderr.read() - cmd.wait() - set_status("done with gofmt") - if len(errors) > 0: - ui.warn("gofmt errors:\n" + errors.rstrip() + "\n") - return - if len(data) > 0: - msg = "gofmt needs to format these files (run hg gofmt):\n" + Indent(data, "\t").rstrip() - if just_warn: - ui.warn("warning: " + msg + "\n") - else: - raise hg_util.Abort(msg) - return - -# Check that *.[chys] files indent using tabs. -def CheckTabfmt(ui, repo, files, just_warn): - files = [f for f in files if f.startswith('src/') and re.search(r"\.[chys]$", f) and not re.search(r"\.tab\.[ch]$", f)] - if not files: - return - cwd = os.getcwd() - files = [RelativePath(repo.root + '/' + f, cwd) for f in files] - files = [f for f in files if os.access(f, 0)] - badfiles = [] - for f in files: - try: - for line in open(f, 'r'): - # Four leading spaces is enough to complain about, - # except that some Plan 9 code uses four spaces as the label indent, - # so allow that. - if line.startswith(' ') and not re.match(' [A-Za-z0-9_]+:', line): - badfiles.append(f) - break - except: - # ignore cannot open file, etc. - pass - if len(badfiles) > 0: - msg = "these files use spaces for indentation (use tabs instead):\n\t" + "\n\t".join(badfiles) - if just_warn: - ui.warn("warning: " + msg + "\n") - else: - raise hg_util.Abort(msg) - return - -####################################################################### -# CONTRIBUTORS file parsing - -contributorsCache = None -contributorsURL = None - -def ReadContributors(ui, repo): - global contributorsCache - if contributorsCache is not None: - return contributorsCache - - try: - if contributorsURL is not None: - opening = contributorsURL - f = urllib2.urlopen(contributorsURL) - else: - opening = repo.root + '/CONTRIBUTORS' - f = open(repo.root + '/CONTRIBUTORS', 'r') - except: - ui.write("warning: cannot open %s: %s\n" % (opening, ExceptionDetail())) - return {} - - contributors = {} - for line in f: - # CONTRIBUTORS is a list of lines like: - # Person - # Person - # The first email address is the one used in commit logs. - if line.startswith('#'): - continue - m = re.match(r"([^<>]+\S)\s+(<[^<>\s]+>)((\s+<[^<>\s]+>)*)\s*$", line) - if m: - name = m.group(1) - email = m.group(2)[1:-1] - contributors[email.lower()] = (name, email) - for extra in m.group(3).split(): - contributors[extra[1:-1].lower()] = (name, email) - - contributorsCache = contributors - return contributors - -def CheckContributor(ui, repo, user=None): - set_status("checking CONTRIBUTORS file") - user, userline = FindContributor(ui, repo, user, warn=False) - if not userline: - raise hg_util.Abort("cannot find %s in CONTRIBUTORS" % (user,)) - return userline - -def FindContributor(ui, repo, user=None, warn=True): - if not user: - user = ui.config("ui", "username") - if not user: - raise hg_util.Abort("[ui] username is not configured in .hgrc") - user = user.lower() - m = re.match(r".*<(.*)>", user) - if m: - user = m.group(1) - - contributors = ReadContributors(ui, repo) - if user not in contributors: - if warn: - ui.warn("warning: cannot find %s in CONTRIBUTORS\n" % (user,)) - return user, None - - user, email = contributors[user] - return email, "%s <%s>" % (user, email) - -####################################################################### -# Mercurial helper functions. -# Read http://mercurial.selenic.com/wiki/MercurialApi before writing any of these. -# We use the ui.pushbuffer/ui.popbuffer + hg_commands.xxx tricks for all interaction -# with Mercurial. It has proved the most stable as they make changes. - -hgversion = hg_util.version() - -# We require Mercurial 1.9 and suggest Mercurial 2.1. -# The details of the scmutil package changed then, -# so allowing earlier versions would require extra band-aids below. -# Ubuntu 11.10 ships with Mercurial 1.9.1 as the default version. -hg_required = "1.9" -hg_suggested = "2.1" - -old_message = """ - -The code review extension requires Mercurial """+hg_required+""" or newer. -You are using Mercurial """+hgversion+""". - -To install a new Mercurial, visit http://mercurial.selenic.com/downloads/. -""" - -linux_message = """ -You may need to clear your current Mercurial installation by running: - - sudo apt-get remove mercurial mercurial-common - sudo rm -rf /etc/mercurial -""" - -if hgversion < hg_required: - msg = old_message - if os.access("/etc/mercurial", 0): - msg += linux_message - raise hg_util.Abort(msg) - -from mercurial.hg import clean as hg_clean -from mercurial import cmdutil as hg_cmdutil -from mercurial import error as hg_error -from mercurial import match as hg_match -from mercurial import node as hg_node - -class uiwrap(object): - def __init__(self, ui): - self.ui = ui - ui.pushbuffer() - self.oldQuiet = ui.quiet - ui.quiet = True - self.oldVerbose = ui.verbose - ui.verbose = False - def output(self): - ui = self.ui - ui.quiet = self.oldQuiet - ui.verbose = self.oldVerbose - return ui.popbuffer() - -def to_slash(path): - if sys.platform == "win32": - return path.replace('\\', '/') - return path - -def hg_matchPattern(ui, repo, *pats, **opts): - w = uiwrap(ui) - hg_commands.status(ui, repo, *pats, **opts) - text = w.output() - ret = [] - prefix = to_slash(os.path.realpath(repo.root))+'/' - for line in text.split('\n'): - f = line.split() - if len(f) > 1: - if len(pats) > 0: - # Given patterns, Mercurial shows relative to cwd - p = to_slash(os.path.realpath(f[1])) - if not p.startswith(prefix): - print >>sys.stderr, "File %s not in repo root %s.\n" % (p, prefix) - else: - ret.append(p[len(prefix):]) - else: - # Without patterns, Mercurial shows relative to root (what we want) - ret.append(to_slash(f[1])) - return ret - -def hg_heads(ui, repo): - w = uiwrap(ui) - hg_commands.heads(ui, repo) - return w.output() - -noise = [ - "", - "resolving manifests", - "searching for changes", - "couldn't find merge tool hgmerge", - "adding changesets", - "adding manifests", - "adding file changes", - "all local heads known remotely", -] - -def isNoise(line): - line = str(line) - for x in noise: - if line == x: - return True - return False - -def hg_incoming(ui, repo): - w = uiwrap(ui) - ret = hg_commands.incoming(ui, repo, force=False, bundle="") - if ret and ret != 1: - raise hg_util.Abort(ret) - return w.output() - -def hg_log(ui, repo, **opts): - for k in ['date', 'keyword', 'rev', 'user']: - if not opts.has_key(k): - opts[k] = "" - w = uiwrap(ui) - ret = hg_commands.log(ui, repo, **opts) - if ret: - raise hg_util.Abort(ret) - return w.output() - -def hg_outgoing(ui, repo, **opts): - w = uiwrap(ui) - ret = hg_commands.outgoing(ui, repo, **opts) - if ret and ret != 1: - raise hg_util.Abort(ret) - return w.output() - -def hg_pull(ui, repo, **opts): - w = uiwrap(ui) - ui.quiet = False - ui.verbose = True # for file list - err = hg_commands.pull(ui, repo, **opts) - for line in w.output().split('\n'): - if isNoise(line): - continue - if line.startswith('moving '): - line = 'mv ' + line[len('moving '):] - if line.startswith('getting ') and line.find(' to ') >= 0: - line = 'mv ' + line[len('getting '):] - if line.startswith('getting '): - line = '+ ' + line[len('getting '):] - if line.startswith('removing '): - line = '- ' + line[len('removing '):] - ui.write(line + '\n') - return err - -def hg_update(ui, repo, **opts): - w = uiwrap(ui) - ui.quiet = False - ui.verbose = True # for file list - err = hg_commands.update(ui, repo, **opts) - for line in w.output().split('\n'): - if isNoise(line): - continue - if line.startswith('moving '): - line = 'mv ' + line[len('moving '):] - if line.startswith('getting ') and line.find(' to ') >= 0: - line = 'mv ' + line[len('getting '):] - if line.startswith('getting '): - line = '+ ' + line[len('getting '):] - if line.startswith('removing '): - line = '- ' + line[len('removing '):] - ui.write(line + '\n') - return err - -def hg_push(ui, repo, **opts): - w = uiwrap(ui) - ui.quiet = False - ui.verbose = True - err = hg_commands.push(ui, repo, **opts) - for line in w.output().split('\n'): - if not isNoise(line): - ui.write(line + '\n') - return err - -def hg_commit(ui, repo, *pats, **opts): - return hg_commands.commit(ui, repo, *pats, **opts) - -####################################################################### -# Mercurial precommit hook to disable commit except through this interface. - -commit_okay = False - -def precommithook(ui, repo, **opts): - if hgversion >= "2.1": - from mercurial import phases - if repo.ui.config('phases', 'new-commit') >= phases.secret: - return False - if commit_okay: - return False # False means okay. - ui.write("\ncodereview extension enabled; use mail, upload, or submit instead of commit\n\n") - return True - -####################################################################### -# @clnumber file pattern support - -# We replace scmutil.match with the MatchAt wrapper to add the @clnumber pattern. - -match_repo = None -match_ui = None -match_orig = None - -def InstallMatch(ui, repo): - global match_repo - global match_ui - global match_orig - - match_ui = ui - match_repo = repo - - from mercurial import scmutil - match_orig = scmutil.match - scmutil.match = MatchAt - -def MatchAt(ctx, pats=None, opts=None, globbed=False, default='relpath'): - taken = [] - files = [] - pats = pats or [] - opts = opts or {} - - for p in pats: - if p.startswith('@'): - taken.append(p) - clname = p[1:] - if clname == "default": - files = DefaultFiles(match_ui, match_repo, []) - else: - if not GoodCLName(clname): - raise hg_util.Abort("invalid CL name " + clname) - cl, err = LoadCL(match_repo.ui, match_repo, clname, web=False) - if err != '': - raise hg_util.Abort("loading CL " + clname + ": " + err) - if not cl.files: - raise hg_util.Abort("no files in CL " + clname) - files = Add(files, cl.files) - pats = Sub(pats, taken) + ['path:'+f for f in files] - - # work-around for http://selenic.com/hg/rev/785bbc8634f8 - if not hasattr(ctx, 'match'): - ctx = ctx[None] - return match_orig(ctx, pats=pats, opts=opts, globbed=globbed, default=default) - -####################################################################### -# Commands added by code review extension. - -def hgcommand(f): - return f - -####################################################################### -# hg change - -@hgcommand -def change(ui, repo, *pats, **opts): - """create, edit or delete a change list - - Create, edit or delete a change list. - A change list is a group of files to be reviewed and submitted together, - plus a textual description of the change. - Change lists are referred to by simple alphanumeric names. - - Changes must be reviewed before they can be submitted. - - In the absence of options, the change command opens the - change list for editing in the default editor. - - Deleting a change with the -d or -D flag does not affect - the contents of the files listed in that change. To revert - the files listed in a change, use - - hg revert @123456 - - before running hg change -d 123456. - """ - - if codereview_disabled: - raise hg_util.Abort(codereview_disabled) - - dirty = {} - if len(pats) > 0 and GoodCLName(pats[0]): - name = pats[0] - if len(pats) != 1: - raise hg_util.Abort("cannot specify CL name and file patterns") - pats = pats[1:] - cl, err = LoadCL(ui, repo, name, web=True) - if err != '': - raise hg_util.Abort(err) - if not cl.local and (opts["stdin"] or not opts["stdout"]): - raise hg_util.Abort("cannot change non-local CL " + name) - else: - name = "new" - cl = CL("new") - if not workbranch(repo[None].branch()): - raise hg_util.Abort("cannot create CL outside default branch; switch with 'hg update default'") - dirty[cl] = True - files = ChangedFiles(ui, repo, pats, taken=Taken(ui, repo)) - - if opts["delete"] or opts["deletelocal"]: - if opts["delete"] and opts["deletelocal"]: - raise hg_util.Abort("cannot use -d and -D together") - flag = "-d" - if opts["deletelocal"]: - flag = "-D" - if name == "new": - raise hg_util.Abort("cannot use "+flag+" with file patterns") - if opts["stdin"] or opts["stdout"]: - raise hg_util.Abort("cannot use "+flag+" with -i or -o") - if not cl.local: - raise hg_util.Abort("cannot change non-local CL " + name) - if opts["delete"]: - if cl.copied_from: - raise hg_util.Abort("original author must delete CL; hg change -D will remove locally") - PostMessage(ui, cl.name, "*** Abandoned ***", send_mail=cl.mailed) - EditDesc(cl.name, closed=True, private=cl.private) - cl.Delete(ui, repo) - return - - if opts["stdin"]: - s = sys.stdin.read() - clx, line, err = ParseCL(s, name) - if err != '': - raise hg_util.Abort("error parsing change list: line %d: %s" % (line, err)) - if clx.desc is not None: - cl.desc = clx.desc; - dirty[cl] = True - if clx.reviewer is not None: - cl.reviewer = clx.reviewer - dirty[cl] = True - if clx.cc is not None: - cl.cc = clx.cc - dirty[cl] = True - if clx.files is not None: - cl.files = clx.files - dirty[cl] = True - if clx.private != cl.private: - cl.private = clx.private - dirty[cl] = True - - if not opts["stdin"] and not opts["stdout"]: - if name == "new": - cl.files = files - err = EditCL(ui, repo, cl) - if err != "": - raise hg_util.Abort(err) - dirty[cl] = True - - for d, _ in dirty.items(): - name = d.name - d.Flush(ui, repo) - if name == "new": - d.Upload(ui, repo, quiet=True) - - if opts["stdout"]: - ui.write(cl.EditorText()) - elif opts["pending"]: - ui.write(cl.PendingText()) - elif name == "new": - if ui.quiet: - ui.write(cl.name) - else: - ui.write("CL created: " + cl.url + "\n") - return - -####################################################################### -# hg code-login (broken?) - -@hgcommand -def code_login(ui, repo, **opts): - """log in to code review server - - Logs in to the code review server, saving a cookie in - a file in your home directory. - """ - if codereview_disabled: - raise hg_util.Abort(codereview_disabled) - - MySend(None) - -####################################################################### -# hg clpatch / undo / release-apply / download -# All concerned with applying or unapplying patches to the repository. - -@hgcommand -def clpatch(ui, repo, clname, **opts): - """import a patch from the code review server - - Imports a patch from the code review server into the local client. - If the local client has already modified any of the files that the - patch modifies, this command will refuse to apply the patch. - - Submitting an imported patch will keep the original author's - name as the Author: line but add your own name to a Committer: line. - """ - if not workbranch(repo[None].branch()): - raise hg_util.Abort("cannot run hg clpatch outside default branch") - err = clpatch_or_undo(ui, repo, clname, opts, mode="clpatch") - if err: - raise hg_util.Abort(err) - -@hgcommand -def undo(ui, repo, clname, **opts): - """undo the effect of a CL - - Creates a new CL that undoes an earlier CL. - After creating the CL, opens the CL text for editing so that - you can add the reason for the undo to the description. - """ - if not workbranch(repo[None].branch()): - raise hg_util.Abort("cannot run hg undo outside default branch") - err = clpatch_or_undo(ui, repo, clname, opts, mode="undo") - if err: - raise hg_util.Abort(err) - -@hgcommand -def release_apply(ui, repo, clname, **opts): - """apply a CL to the release branch - - Creates a new CL copying a previously committed change - from the main branch to the release branch. - The current client must either be clean or already be in - the release branch. - - The release branch must be created by starting with a - clean client, disabling the code review plugin, and running: - - hg update weekly.YYYY-MM-DD - hg branch release-branch.rNN - hg commit -m 'create release-branch.rNN' - hg push --new-branch - - Then re-enable the code review plugin. - - People can test the release branch by running - - hg update release-branch.rNN - - in a clean client. To return to the normal tree, - - hg update default - - Move changes since the weekly into the release branch - using hg release-apply followed by the usual code review - process and hg submit. - - When it comes time to tag the release, record the - final long-form tag of the release-branch.rNN - in the *default* branch's .hgtags file. That is, run - - hg update default - - and then edit .hgtags as you would for a weekly. - - """ - c = repo[None] - if not releaseBranch: - raise hg_util.Abort("no active release branches") - if c.branch() != releaseBranch: - if c.modified() or c.added() or c.removed(): - raise hg_util.Abort("uncommitted local changes - cannot switch branches") - err = hg_clean(repo, releaseBranch) - if err: - raise hg_util.Abort(err) - try: - err = clpatch_or_undo(ui, repo, clname, opts, mode="backport") - if err: - raise hg_util.Abort(err) - except Exception, e: - hg_clean(repo, "default") - raise e - -def rev2clname(rev): - # Extract CL name from revision description. - # The last line in the description that is a codereview URL is the real one. - # Earlier lines might be part of the user-written description. - all = re.findall('(?m)^https?://codereview.appspot.com/([0-9]+)$', rev.description()) - if len(all) > 0: - return all[-1] - return "" - -undoHeader = """undo CL %s / %s - - - -««« original CL description -""" - -undoFooter = """ -»»» -""" - -backportHeader = """[%s] %s - -««« CL %s / %s -""" - -backportFooter = """ -»»» -""" - -# Implementation of clpatch/undo. -def clpatch_or_undo(ui, repo, clname, opts, mode): - if codereview_disabled: - return codereview_disabled - - if mode == "undo" or mode == "backport": - # Find revision in Mercurial repository. - # Assume CL number is 7+ decimal digits. - # Otherwise is either change log sequence number (fewer decimal digits), - # hexadecimal hash, or tag name. - # Mercurial will fall over long before the change log - # sequence numbers get to be 7 digits long. - if re.match('^[0-9]{7,}$', clname): - found = False - for r in hg_log(ui, repo, keyword="codereview.appspot.com/"+clname, limit=100, template="{node}\n").split(): - rev = repo[r] - # Last line with a code review URL is the actual review URL. - # Earlier ones might be part of the CL description. - n = rev2clname(rev) - if n == clname: - found = True - break - if not found: - return "cannot find CL %s in local repository" % clname - else: - rev = repo[clname] - if not rev: - return "unknown revision %s" % clname - clname = rev2clname(rev) - if clname == "": - return "cannot find CL name in revision description" - - # Create fresh CL and start with patch that would reverse the change. - vers = hg_node.short(rev.node()) - cl = CL("new") - desc = str(rev.description()) - if mode == "undo": - cl.desc = (undoHeader % (clname, vers)) + desc + undoFooter - else: - cl.desc = (backportHeader % (releaseBranch, line1(desc), clname, vers)) + desc + undoFooter - v1 = vers - v0 = hg_node.short(rev.parents()[0].node()) - if mode == "undo": - arg = v1 + ":" + v0 - else: - vers = v0 - arg = v0 + ":" + v1 - patch = RunShell(["hg", "diff", "--git", "-r", arg]) - - else: # clpatch - cl, vers, patch, err = DownloadCL(ui, repo, clname) - if err != "": - return err - if patch == emptydiff: - return "codereview issue %s has no diff" % clname - - # find current hg version (hg identify) - ctx = repo[None] - parents = ctx.parents() - id = '+'.join([hg_node.short(p.node()) for p in parents]) - - # if version does not match the patch version, - # try to update the patch line numbers. - if vers != "" and id != vers: - # "vers in repo" gives the wrong answer - # on some versions of Mercurial. Instead, do the actual - # lookup and catch the exception. - try: - repo[vers].description() - except: - return "local repository is out of date; sync to get %s" % (vers) - patch1, err = portPatch(repo, patch, vers, id) - if err != "": - if not opts["ignore_hgapplydiff_failure"]: - return "codereview issue %s is out of date: %s (%s->%s)" % (clname, err, vers, id) - else: - patch = patch1 - argv = ["hgapplydiff"] - if opts["no_incoming"] or mode == "backport": - argv += ["--checksync=false"] - try: - cmd = subprocess.Popen(argv, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, close_fds=sys.platform != "win32") - except: - return "hgapplydiff: " + ExceptionDetail() + "\nInstall hgapplydiff with:\n$ go get golang.org/x/codereview/cmd/hgapplydiff\n" - - out, err = cmd.communicate(patch) - if cmd.returncode != 0 and not opts["ignore_hgapplydiff_failure"]: - return "hgapplydiff failed" - cl.local = True - cl.files = out.strip().split() - if not cl.files and not opts["ignore_hgapplydiff_failure"]: - return "codereview issue %s has no changed files" % clname - files = ChangedFiles(ui, repo, []) - extra = Sub(cl.files, files) - if extra: - ui.warn("warning: these files were listed in the patch but not changed:\n\t" + "\n\t".join(extra) + "\n") - cl.Flush(ui, repo) - if mode == "undo": - err = EditCL(ui, repo, cl) - if err != "": - return "CL created, but error editing: " + err - cl.Flush(ui, repo) - else: - ui.write(cl.PendingText() + "\n") - -# portPatch rewrites patch from being a patch against -# oldver to being a patch against newver. -def portPatch(repo, patch, oldver, newver): - lines = patch.splitlines(True) # True = keep \n - delta = None - for i in range(len(lines)): - line = lines[i] - if line.startswith('--- a/'): - file = line[6:-1] - delta = fileDeltas(repo, file, oldver, newver) - if not delta or not line.startswith('@@ '): - continue - # @@ -x,y +z,w @@ means the patch chunk replaces - # the original file's line numbers x up to x+y with the - # line numbers z up to z+w in the new file. - # Find the delta from x in the original to the same - # line in the current version and add that delta to both - # x and z. - m = re.match('@@ -([0-9]+),([0-9]+) \+([0-9]+),([0-9]+) @@', line) - if not m: - return None, "error parsing patch line numbers" - n1, len1, n2, len2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)) - d, err = lineDelta(delta, n1, len1) - if err != "": - return "", err - n1 += d - n2 += d - lines[i] = "@@ -%d,%d +%d,%d @@\n" % (n1, len1, n2, len2) - - newpatch = ''.join(lines) - return newpatch, "" - -# fileDelta returns the line number deltas for the given file's -# changes from oldver to newver. -# The deltas are a list of (n, len, newdelta) triples that say -# lines [n, n+len) were modified, and after that range the -# line numbers are +newdelta from what they were before. -def fileDeltas(repo, file, oldver, newver): - cmd = ["hg", "diff", "--git", "-r", oldver + ":" + newver, "path:" + file] - data = RunShell(cmd, silent_ok=True) - deltas = [] - for line in data.splitlines(): - m = re.match('@@ -([0-9]+),([0-9]+) \+([0-9]+),([0-9]+) @@', line) - if not m: - continue - n1, len1, n2, len2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)) - deltas.append((n1, len1, n2+len2-(n1+len1))) - return deltas - -# lineDelta finds the appropriate line number delta to apply to the lines [n, n+len). -# It returns an error if those lines were rewritten by the patch. -def lineDelta(deltas, n, len): - d = 0 - for (old, oldlen, newdelta) in deltas: - if old >= n+len: - break - if old+len > n: - return 0, "patch and recent changes conflict" - d = newdelta - return d, "" - -@hgcommand -def download(ui, repo, clname, **opts): - """download a change from the code review server - - Download prints a description of the given change list - followed by its diff, downloaded from the code review server. - """ - if codereview_disabled: - raise hg_util.Abort(codereview_disabled) - - cl, vers, patch, err = DownloadCL(ui, repo, clname) - if err != "": - return err - ui.write(cl.EditorText() + "\n") - ui.write(patch + "\n") - return - -####################################################################### -# hg file - -@hgcommand -def file(ui, repo, clname, pat, *pats, **opts): - """assign files to or remove files from a change list - - Assign files to or (with -d) remove files from a change list. - - The -d option only removes files from the change list. - It does not edit them or remove them from the repository. - """ - if codereview_disabled: - raise hg_util.Abort(codereview_disabled) - - pats = tuple([pat] + list(pats)) - if not GoodCLName(clname): - return "invalid CL name " + clname - - dirty = {} - cl, err = LoadCL(ui, repo, clname, web=False) - if err != '': - return err - if not cl.local: - return "cannot change non-local CL " + clname - - files = ChangedFiles(ui, repo, pats) - - if opts["delete"]: - oldfiles = Intersect(files, cl.files) - if oldfiles: - if not ui.quiet: - ui.status("# Removing files from CL. To undo:\n") - ui.status("# cd %s\n" % (repo.root)) - for f in oldfiles: - ui.status("# hg file %s %s\n" % (cl.name, f)) - cl.files = Sub(cl.files, oldfiles) - cl.Flush(ui, repo) - else: - ui.status("no such files in CL") - return - - if not files: - return "no such modified files" - - files = Sub(files, cl.files) - taken = Taken(ui, repo) - warned = False - for f in files: - if f in taken: - if not warned and not ui.quiet: - ui.status("# Taking files from other CLs. To undo:\n") - ui.status("# cd %s\n" % (repo.root)) - warned = True - ocl = taken[f] - if not ui.quiet: - ui.status("# hg file %s %s\n" % (ocl.name, f)) - if ocl not in dirty: - ocl.files = Sub(ocl.files, files) - dirty[ocl] = True - cl.files = Add(cl.files, files) - dirty[cl] = True - for d, _ in dirty.items(): - d.Flush(ui, repo) - return - -####################################################################### -# hg gofmt - -@hgcommand -def gofmt(ui, repo, *pats, **opts): - """apply gofmt to modified files - - Applies gofmt to the modified files in the repository that match - the given patterns. - """ - if codereview_disabled: - raise hg_util.Abort(codereview_disabled) - - files = ChangedExistingFiles(ui, repo, pats, opts) - files = gofmt_required(files) - if not files: - ui.status("no modified go files\n") - return - cwd = os.getcwd() - files = [RelativePath(repo.root + '/' + f, cwd) for f in files] - try: - cmd = ["gofmt", "-l"] - if not opts["list"]: - cmd += ["-w"] - if subprocess.call(cmd + files) != 0: - raise hg_util.Abort("gofmt did not exit cleanly") - except hg_error.Abort, e: - raise - except: - raise hg_util.Abort("gofmt: " + ExceptionDetail()) - return - -def gofmt_required(files): - return [f for f in files if (not f.startswith('test/') or f.startswith('test/bench/')) and f.endswith('.go')] - -####################################################################### -# hg mail - -@hgcommand -def mail(ui, repo, *pats, **opts): - """mail a change for review - - Uploads a patch to the code review server and then sends mail - to the reviewer and CC list asking for a review. - """ - if codereview_disabled: - raise hg_util.Abort(codereview_disabled) - - cl, err = CommandLineCL(ui, repo, pats, opts, op="mail", defaultcc=defaultcc) - if err != "": - raise hg_util.Abort(err) - cl.Upload(ui, repo, gofmt_just_warn=True) - if not cl.reviewer: - # If no reviewer is listed, assign the review to defaultcc. - # This makes sure that it appears in the - # codereview.appspot.com/user/defaultcc - # page, so that it doesn't get dropped on the floor. - if not defaultcc or cl.private: - raise hg_util.Abort("no reviewers listed in CL") - cl.cc = Sub(cl.cc, defaultcc) - cl.reviewer = defaultcc - cl.Flush(ui, repo) - - if cl.files == []: - raise hg_util.Abort("no changed files, not sending mail") - - cl.Mail(ui, repo) - -####################################################################### -# hg p / hg pq / hg ps / hg pending - -@hgcommand -def ps(ui, repo, *pats, **opts): - """alias for hg p --short - """ - opts['short'] = True - return pending(ui, repo, *pats, **opts) - -@hgcommand -def pq(ui, repo, *pats, **opts): - """alias for hg p --quick - """ - opts['quick'] = True - return pending(ui, repo, *pats, **opts) - -@hgcommand -def pending(ui, repo, *pats, **opts): - """show pending changes - - Lists pending changes followed by a list of unassigned but modified files. - """ - if codereview_disabled: - raise hg_util.Abort(codereview_disabled) - - quick = opts.get('quick', False) - short = opts.get('short', False) - m = LoadAllCL(ui, repo, web=not quick and not short) - names = m.keys() - names.sort() - for name in names: - cl = m[name] - if short: - ui.write(name + "\t" + line1(cl.desc) + "\n") - else: - ui.write(cl.PendingText(quick=quick) + "\n") - - if short: - return 0 - files = DefaultFiles(ui, repo, []) - if len(files) > 0: - s = "Changed files not in any CL:\n" - for f in files: - s += "\t" + f + "\n" - ui.write(s) - -####################################################################### -# hg submit - -def need_sync(): - raise hg_util.Abort("local repository out of date; must sync before submit") - -def branch_prefix(ui, repo): - prefix = "" - branch = repo[None].branch() - if branch.startswith("dev."): - prefix = "[" + branch + "] " - return prefix - -@hgcommand -def submit(ui, repo, *pats, **opts): - """submit change to remote repository - - Submits change to remote repository. - Bails out if the local repository is not in sync with the remote one. - """ - if codereview_disabled: - raise hg_util.Abort(codereview_disabled) - - # We already called this on startup but sometimes Mercurial forgets. - set_mercurial_encoding_to_utf8() - - if not opts["no_incoming"] and hg_incoming(ui, repo): - need_sync() - - cl, err = CommandLineCL(ui, repo, pats, opts, op="submit", defaultcc=defaultcc) - if err != "": - raise hg_util.Abort(err) - - user = None - if cl.copied_from: - user = cl.copied_from - userline = CheckContributor(ui, repo, user) - typecheck(userline, str) - - about = "" - - if not cl.lgtm and not opts.get('tbr') and needLGTM(cl): - raise hg_util.Abort("this CL has not been LGTM'ed") - if cl.lgtm: - about += "LGTM=" + JoinComma([CutDomain(who) for (who, line, approval) in cl.lgtm if approval]) + "\n" - reviewer = cl.reviewer - if opts.get('tbr'): - tbr = SplitCommaSpace(opts.get('tbr')) - for name in tbr: - if name.startswith('golang-'): - raise hg_util.Abort("--tbr requires a person, not a mailing list") - cl.reviewer = Add(cl.reviewer, tbr) - about += "TBR=" + JoinComma([CutDomain(s) for s in tbr]) + "\n" - if reviewer: - about += "R=" + JoinComma([CutDomain(s) for s in reviewer]) + "\n" - if cl.cc: - about += "CC=" + JoinComma([CutDomain(s) for s in cl.cc]) + "\n" - - if not cl.reviewer and needLGTM(cl): - raise hg_util.Abort("no reviewers listed in CL") - - if not cl.local: - raise hg_util.Abort("cannot submit non-local CL") - - # upload, to sync current patch and also get change number if CL is new. - if not cl.copied_from: - cl.Upload(ui, repo, gofmt_just_warn=True) - - # check gofmt for real; allowed upload to warn in order to save CL. - cl.Flush(ui, repo) - CheckFormat(ui, repo, cl.files) - - about += "%s%s\n" % (server_url_base, cl.name) - - if cl.copied_from: - about += "\nCommitter: " + CheckContributor(ui, repo, None) + "\n" - typecheck(about, str) - - if not cl.mailed and not cl.copied_from: # in case this is TBR - cl.Mail(ui, repo) - - # submit changes locally - message = branch_prefix(ui, repo) + cl.desc.rstrip() + "\n\n" + about - typecheck(message, str) - - set_status("pushing " + cl.name + " to remote server") - - if hg_outgoing(ui, repo): - raise hg_util.Abort("local repository corrupt or out-of-phase with remote: found outgoing changes") - - old_heads = len(hg_heads(ui, repo).split()) - - # Normally we commit listing the specific files in the CL. - # If there are no changed files other than those in the CL, however, - # let hg build the list, because then committing a merge works. - # (You cannot name files for a merge commit, even if you name - # all the files that would be committed by not naming any.) - files = ['path:'+f for f in cl.files] - if ChangedFiles(ui, repo, []) == cl.files: - files = [] - - global commit_okay - commit_okay = True - ret = hg_commit(ui, repo, *files, message=message, user=userline) - commit_okay = False - if ret: - raise hg_util.Abort("nothing changed") - - node = repo["-1"].node() - # push to remote; if it fails for any reason, roll back - try: - new_heads = len(hg_heads(ui, repo).split()) - if cl.desc.find("create new branch") < 0 and old_heads != new_heads and not (old_heads == 0 and new_heads == 1): - # Created new head, so we weren't up to date. - need_sync() - - # Push changes to remote. If it works, we're committed. If not, roll back. - try: - if hg_push(ui, repo, new_branch=cl.desc.find("create new branch")>=0): - raise hg_util.Abort("push error") - except hg_error.Abort, e: - if e.message.find("push creates new heads") >= 0: - # Remote repository had changes we missed. - need_sync() - raise - except urllib2.HTTPError, e: - print >>sys.stderr, "pushing to remote server failed; do you have commit permissions?" - raise - except: - real_rollback() - raise - - # We're committed. Upload final patch, close review, add commit message. - changeURL = hg_node.short(node) - url = ui.expandpath("default") - m = re.match("(^https?://([^@/]+@)?([^.]+)\.googlecode\.com/hg/?)" + "|" + - "(^https?://([^@/]+@)?code\.google\.com/p/([^/.]+)(\.[^./]+)?/?)", url) - if m: - if m.group(1): # prj.googlecode.com/hg/ case - changeURL = "https://code.google.com/p/%s/source/detail?r=%s" % (m.group(3), changeURL) - elif m.group(4) and m.group(7): # code.google.com/p/prj.subrepo/ case - changeURL = "https://code.google.com/p/%s/source/detail?r=%s&repo=%s" % (m.group(6), changeURL, m.group(7)[1:]) - elif m.group(4): # code.google.com/p/prj/ case - changeURL = "https://code.google.com/p/%s/source/detail?r=%s" % (m.group(6), changeURL) - else: - print >>sys.stderr, "URL: ", url - else: - print >>sys.stderr, "URL: ", url - pmsg = "*** Submitted as " + changeURL + " ***\n\n" + message - - # When posting, move reviewers to CC line, - # so that the issue stops showing up in their "My Issues" page. - PostMessage(ui, cl.name, pmsg, reviewers="", cc=JoinComma(cl.reviewer+cl.cc)) - - if not cl.copied_from: - EditDesc(cl.name, closed=True, private=cl.private) - cl.Delete(ui, repo) - - c = repo[None] - if c.branch() == releaseBranch and not c.modified() and not c.added() and not c.removed(): - ui.write("switching from %s to default branch.\n" % releaseBranch) - err = hg_clean(repo, "default") - if err: - return err - return 0 - -def needLGTM(cl): - rev = cl.reviewer - isGobot = 'gobot' in rev or 'gobot@swtch.com' in rev or 'gobot@golang.org' in rev - - # A+C CLs generated by addca do not need LGTM - if cl.desc.startswith('A+C:') and 'Generated by a+c.' in cl.desc and isGobot: - return False - - # CLs modifying only go1.x.txt do not need LGTM - if len(cl.files) == 1 and cl.files[0].startswith('doc/go1.') and cl.files[0].endswith('.txt'): - return False - - # Other CLs need LGTM - return True - -####################################################################### -# hg sync - -@hgcommand -def sync(ui, repo, **opts): - """synchronize with remote repository - - Incorporates recent changes from the remote repository - into the local repository. - """ - if codereview_disabled: - raise hg_util.Abort(codereview_disabled) - - if not opts["local"]: - # If there are incoming CLs, pull -u will do the update. - # If there are no incoming CLs, do hg update to make sure - # that an update always happens regardless. This is less - # surprising than update depending on incoming CLs. - # It is important not to do both hg pull -u and hg update - # in the same command, because the hg update will end - # up marking resolve conflicts from the hg pull -u as resolved, - # causing files with <<< >>> markers to not show up in - # hg resolve -l. Yay Mercurial. - if hg_incoming(ui, repo): - err = hg_pull(ui, repo, update=True) - else: - err = hg_update(ui, repo) - if err: - return err - sync_changes(ui, repo) - -def sync_changes(ui, repo): - # Look through recent change log descriptions to find - # potential references to http://.*/our-CL-number. - # Double-check them by looking at the Rietveld log. - for rev in hg_log(ui, repo, limit=100, template="{node}\n").split(): - desc = repo[rev].description().strip() - for clname in re.findall('(?m)^https?://(?:[^\n]+)/([0-9]+)$', desc): - if IsLocalCL(ui, repo, clname) and IsRietveldSubmitted(ui, clname, repo[rev].hex()): - ui.warn("CL %s submitted as %s; closing\n" % (clname, repo[rev])) - cl, err = LoadCL(ui, repo, clname, web=False) - if err != "": - ui.warn("loading CL %s: %s\n" % (clname, err)) - continue - if not cl.copied_from: - EditDesc(cl.name, closed=True, private=cl.private) - cl.Delete(ui, repo) - - # Remove files that are not modified from the CLs in which they appear. - all = LoadAllCL(ui, repo, web=False) - changed = ChangedFiles(ui, repo, []) - for cl in all.values(): - extra = Sub(cl.files, changed) - if extra: - ui.warn("Removing unmodified files from CL %s:\n" % (cl.name,)) - for f in extra: - ui.warn("\t%s\n" % (f,)) - cl.files = Sub(cl.files, extra) - cl.Flush(ui, repo) - if not cl.files: - if not cl.copied_from: - ui.warn("CL %s has no files; delete (abandon) with hg change -d %s\n" % (cl.name, cl.name)) - else: - ui.warn("CL %s has no files; delete locally with hg change -D %s\n" % (cl.name, cl.name)) - return 0 - -####################################################################### -# hg upload - -@hgcommand -def upload(ui, repo, name, **opts): - """upload diffs to the code review server - - Uploads the current modifications for a given change to the server. - """ - if codereview_disabled: - raise hg_util.Abort(codereview_disabled) - - repo.ui.quiet = True - cl, err = LoadCL(ui, repo, name, web=True) - if err != "": - raise hg_util.Abort(err) - if not cl.local: - raise hg_util.Abort("cannot upload non-local change") - cl.Upload(ui, repo) - print "%s%s\n" % (server_url_base, cl.name) - return 0 - -####################################################################### -# Table of commands, supplied to Mercurial for installation. - -review_opts = [ - ('r', 'reviewer', '', 'add reviewer'), - ('', 'cc', '', 'add cc'), - ('', 'tbr', '', 'add future reviewer'), - ('m', 'message', '', 'change description (for new change)'), -] - -cmdtable = { - # The ^ means to show this command in the help text that - # is printed when running hg with no arguments. - "^change": ( - change, - [ - ('d', 'delete', None, 'delete existing change list'), - ('D', 'deletelocal', None, 'delete locally, but do not change CL on server'), - ('i', 'stdin', None, 'read change list from standard input'), - ('o', 'stdout', None, 'print change list to standard output'), - ('p', 'pending', None, 'print pending summary to standard output'), - ], - "[-d | -D] [-i] [-o] change# or FILE ..." - ), - "^clpatch": ( - clpatch, - [ - ('', 'ignore_hgapplydiff_failure', None, 'create CL metadata even if hgapplydiff fails'), - ('', 'no_incoming', None, 'disable check for incoming changes'), - ], - "change#" - ), - # Would prefer to call this codereview-login, but then - # hg help codereview prints the help for this command - # instead of the help for the extension. - "code-login": ( - code_login, - [], - "", - ), - "^download": ( - download, - [], - "change#" - ), - "^file": ( - file, - [ - ('d', 'delete', None, 'delete files from change list (but not repository)'), - ], - "[-d] change# FILE ..." - ), - "^gofmt": ( - gofmt, - [ - ('l', 'list', None, 'list files that would change, but do not edit them'), - ], - "FILE ..." - ), - "^pending|p": ( - pending, - [ - ('s', 'short', False, 'show short result form'), - ('', 'quick', False, 'do not consult codereview server'), - ], - "[FILE ...]" - ), - "^ps": ( - ps, - [], - "[FILE ...]" - ), - "^pq": ( - pq, - [], - "[FILE ...]" - ), - "^mail": ( - mail, - review_opts + [ - ] + hg_commands.walkopts, - "[-r reviewer] [--cc cc] [change# | file ...]" - ), - "^release-apply": ( - release_apply, - [ - ('', 'ignore_hgapplydiff_failure', None, 'create CL metadata even if hgapplydiff fails'), - ('', 'no_incoming', None, 'disable check for incoming changes'), - ], - "change#" - ), - # TODO: release-start, release-tag, weekly-tag - "^submit": ( - submit, - review_opts + [ - ('', 'no_incoming', None, 'disable initial incoming check (for testing)'), - ] + hg_commands.walkopts + hg_commands.commitopts + hg_commands.commitopts2, - "[-r reviewer] [--cc cc] [change# | file ...]" - ), - "^sync": ( - sync, - [ - ('', 'local', None, 'do not pull changes from remote repository') - ], - "[--local]", - ), - "^undo": ( - undo, - [ - ('', 'ignore_hgapplydiff_failure', None, 'create CL metadata even if hgapplydiff fails'), - ('', 'no_incoming', None, 'disable check for incoming changes'), - ], - "change#" - ), - "^upload": ( - upload, - [], - "change#" - ), -} - -####################################################################### -# Mercurial extension initialization - -def norollback(*pats, **opts): - """(disabled when using this extension)""" - raise hg_util.Abort("codereview extension enabled; use undo instead of rollback") - -codereview_init = False - -def uisetup(ui): - global testing - testing = ui.config("codereview", "testing") - # Disable the Mercurial commands that might change the repository. - # Only commands in this extension are supposed to do that. - ui.setconfig("hooks", "pre-commit.codereview", precommithook) # runs before 'hg commit' - ui.setconfig("hooks", "precommit.codereview", precommithook) # catches all cases - -def reposetup(ui, repo): - global codereview_disabled - global defaultcc - - # reposetup gets called both for the local repository - # and also for any repository we are pulling or pushing to. - # Only initialize the first time. - global codereview_init - if codereview_init: - return - codereview_init = True - start_status_thread() - - # Read repository-specific options from lib/codereview/codereview.cfg or codereview.cfg. - root = '' - try: - root = repo.root - except: - # Yes, repo might not have root; see issue 959. - codereview_disabled = 'codereview disabled: repository has no root' - return - - repo_config_path = '' - p1 = root + '/lib/codereview/codereview.cfg' - p2 = root + '/codereview.cfg' - if os.access(p1, os.F_OK): - repo_config_path = p1 - else: - repo_config_path = p2 - try: - f = open(repo_config_path) - for line in f: - if line.startswith('defaultcc:'): - defaultcc = SplitCommaSpace(line[len('defaultcc:'):]) - if line.startswith('contributors:'): - global contributorsURL - contributorsURL = line[len('contributors:'):].strip() - except: - codereview_disabled = 'codereview disabled: cannot open ' + repo_config_path - return - - remote = ui.config("paths", "default", "") - if remote.find("://") < 0 and not testing: - raise hg_util.Abort("codereview: default path '%s' is not a URL" % (remote,)) - - InstallMatch(ui, repo) - RietveldSetup(ui, repo) - - # Rollback removes an existing commit. Don't do that either. - global real_rollback - real_rollback = repo.rollback - repo.rollback = norollback - - -####################################################################### -# Wrappers around upload.py for interacting with Rietveld - -from HTMLParser import HTMLParser - -# HTML form parser -class FormParser(HTMLParser): - def __init__(self): - self.map = {} - self.curtag = None - self.curdata = None - HTMLParser.__init__(self) - def handle_starttag(self, tag, attrs): - if tag == "input": - key = None - value = '' - for a in attrs: - if a[0] == 'name': - key = a[1] - if a[0] == 'value': - value = a[1] - if key is not None: - self.map[key] = value - if tag == "textarea": - key = None - for a in attrs: - if a[0] == 'name': - key = a[1] - if key is not None: - self.curtag = key - self.curdata = '' - def handle_endtag(self, tag): - if tag == "textarea" and self.curtag is not None: - self.map[self.curtag] = self.curdata - self.curtag = None - self.curdata = None - def handle_charref(self, name): - self.handle_data(unichr(int(name))) - def handle_entityref(self, name): - import htmlentitydefs - if name in htmlentitydefs.entitydefs: - self.handle_data(htmlentitydefs.entitydefs[name]) - else: - self.handle_data("&" + name + ";") - def handle_data(self, data): - if self.curdata is not None: - self.curdata += data - -def JSONGet(ui, path): - try: - data = MySend(path, force_auth=False) - typecheck(data, str) - d = fix_json(json.loads(data)) - except: - ui.warn("JSONGet %s: %s\n" % (path, ExceptionDetail())) - return None - return d - -# Clean up json parser output to match our expectations: -# * all strings are UTF-8-encoded str, not unicode. -# * missing fields are missing, not None, -# so that d.get("foo", defaultvalue) works. -def fix_json(x): - if type(x) in [str, int, float, bool, type(None)]: - pass - elif type(x) is unicode: - x = x.encode("utf-8") - elif type(x) is list: - for i in range(len(x)): - x[i] = fix_json(x[i]) - elif type(x) is dict: - todel = [] - for k in x: - if x[k] is None: - todel.append(k) - else: - x[k] = fix_json(x[k]) - for k in todel: - del x[k] - else: - raise hg_util.Abort("unknown type " + str(type(x)) + " in fix_json") - if type(x) is str: - x = x.replace('\r\n', '\n') - return x - -def IsRietveldSubmitted(ui, clname, hex): - dict = JSONGet(ui, "/api/" + clname + "?messages=true") - if dict is None: - return False - for msg in dict.get("messages", []): - text = msg.get("text", "") - regex = '\*\*\* Submitted as [^*]*?r=([0-9a-f]+)[^ ]* \*\*\*' - if testing: - regex = '\*\*\* Submitted as ([0-9a-f]+) \*\*\*' - m = re.match(regex, text) - if m is not None and len(m.group(1)) >= 8 and hex.startswith(m.group(1)): - return True - return False - -def IsRietveldMailed(cl): - for msg in cl.dict.get("messages", []): - if msg.get("text", "").find("I'd like you to review this change") >= 0: - return True - return False - -def DownloadCL(ui, repo, clname): - set_status("downloading CL " + clname) - cl, err = LoadCL(ui, repo, clname, web=True) - if err != "": - return None, None, None, "error loading CL %s: %s" % (clname, err) - - # Find most recent diff - diffs = cl.dict.get("patchsets", []) - if not diffs: - return None, None, None, "CL has no patch sets" - patchid = diffs[-1] - - patchset = JSONGet(ui, "/api/" + clname + "/" + str(patchid)) - if patchset is None: - return None, None, None, "error loading CL patchset %s/%d" % (clname, patchid) - if patchset.get("patchset", 0) != patchid: - return None, None, None, "malformed patchset information" - - vers = "" - msg = patchset.get("message", "").split() - if len(msg) >= 3 and msg[0] == "diff" and msg[1] == "-r": - vers = msg[2] - diff = "/download/issue" + clname + "_" + str(patchid) + ".diff" - - diffdata = MySend(diff, force_auth=False) - - # Print warning if email is not in CONTRIBUTORS file. - email = cl.dict.get("owner_email", "") - if not email: - return None, None, None, "cannot find owner for %s" % (clname) - him = FindContributor(ui, repo, email) - me = FindContributor(ui, repo, None) - if him == me: - cl.mailed = IsRietveldMailed(cl) - else: - cl.copied_from = email - - return cl, vers, diffdata, "" - -def MySend(request_path, payload=None, - content_type="application/octet-stream", - timeout=None, force_auth=True, - **kwargs): - """Run MySend1 maybe twice, because Rietveld is unreliable.""" - try: - return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs) - except Exception, e: - if type(e) != urllib2.HTTPError or e.code != 500: # only retry on HTTP 500 error - raise - print >>sys.stderr, "Loading "+request_path+": "+ExceptionDetail()+"; trying again in 2 seconds." - time.sleep(2) - return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs) - -# Like upload.py Send but only authenticates when the -# redirect is to www.google.com/accounts. This keeps -# unnecessary redirects from happening during testing. -def MySend1(request_path, payload=None, - content_type="application/octet-stream", - timeout=None, force_auth=True, - **kwargs): - """Sends an RPC and returns the response. - - Args: - request_path: The path to send the request to, eg /api/appversion/create. - payload: The body of the request, or None to send an empty request. - content_type: The Content-Type header to use. - timeout: timeout in seconds; default None i.e. no timeout. - (Note: for large requests on OS X, the timeout doesn't work right.) - kwargs: Any keyword arguments are converted into query string parameters. - - Returns: - The response body, as a string. - """ - # TODO: Don't require authentication. Let the server say - # whether it is necessary. - global rpc - if rpc == None: - rpc = GetRpcServer(upload_options) - self = rpc - if not self.authenticated and force_auth: - self._Authenticate() - if request_path is None: - return - if timeout is None: - timeout = 30 # seconds - - old_timeout = socket.getdefaulttimeout() - socket.setdefaulttimeout(timeout) - try: - tries = 0 - while True: - tries += 1 - args = dict(kwargs) - url = "https://%s%s" % (self.host, request_path) - if testing: - url = url.replace("https://", "http://") - if args: - url += "?" + urllib.urlencode(args) - req = self._CreateRequest(url=url, data=payload) - req.add_header("Content-Type", content_type) - try: - f = self.opener.open(req) - response = f.read() - f.close() - # Translate \r\n into \n, because Rietveld doesn't. - response = response.replace('\r\n', '\n') - # who knows what urllib will give us - if type(response) == unicode: - response = response.encode("utf-8") - typecheck(response, str) - return response - except urllib2.HTTPError, e: - if tries > 3: - raise - elif e.code == 401: - self._Authenticate() - elif e.code == 302: - loc = e.info()["location"] - if not loc.startswith('https://www.google.com/a') or loc.find('/ServiceLogin') < 0: - return '' - self._Authenticate() - else: - raise - finally: - socket.setdefaulttimeout(old_timeout) - -def GetForm(url): - f = FormParser() - f.feed(ustr(MySend(url))) # f.feed wants unicode - f.close() - # convert back to utf-8 to restore sanity - m = {} - for k,v in f.map.items(): - m[k.encode("utf-8")] = v.replace("\r\n", "\n").encode("utf-8") - return m - -def EditDesc(issue, subject=None, desc=None, reviewers=None, cc=None, closed=False, private=False): - set_status("uploading change to description") - form_fields = GetForm("/" + issue + "/edit") - if subject is not None: - form_fields['subject'] = subject - if desc is not None: - form_fields['description'] = desc - if reviewers is not None: - form_fields['reviewers'] = reviewers - if cc is not None: - form_fields['cc'] = cc - if closed: - form_fields['closed'] = "checked" - if private: - form_fields['private'] = "checked" - ctype, body = EncodeMultipartFormData(form_fields.items(), []) - response = MySend("/" + issue + "/edit", body, content_type=ctype) - if response != "": - print >>sys.stderr, "Error editing description:\n" + "Sent form: \n", form_fields, "\n", response - sys.exit(2) - -def PostMessage(ui, issue, message, reviewers=None, cc=None, send_mail=True, subject=None): - set_status("uploading message") - form_fields = GetForm("/" + issue + "/publish") - if reviewers is not None: - form_fields['reviewers'] = reviewers - if cc is not None: - form_fields['cc'] = cc - if send_mail: - form_fields['send_mail'] = "checked" - else: - del form_fields['send_mail'] - if subject is not None: - form_fields['subject'] = subject - form_fields['message'] = message - - form_fields['message_only'] = '1' # Don't include draft comments - if reviewers is not None or cc is not None: - form_fields['message_only'] = '' # Must set '' in order to override cc/reviewer - ctype = "applications/x-www-form-urlencoded" - body = urllib.urlencode(form_fields) - response = MySend("/" + issue + "/publish", body, content_type=ctype) - if response != "": - print response - sys.exit(2) - -class opt(object): - pass - -def RietveldSetup(ui, repo): - global force_google_account - global rpc - global server - global server_url_base - global upload_options - global verbosity - - if not ui.verbose: - verbosity = 0 - - # Config options. - x = ui.config("codereview", "server") - if x is not None: - server = x - - # TODO(rsc): Take from ui.username? - email = None - x = ui.config("codereview", "email") - if x is not None: - email = x - - server_url_base = "https://" + server + "/" - if testing: - server_url_base = server_url_base.replace("https://", "http://") - - force_google_account = ui.configbool("codereview", "force_google_account", False) - - upload_options = opt() - upload_options.email = email - upload_options.host = None - upload_options.verbose = 0 - upload_options.description = None - upload_options.description_file = None - upload_options.reviewers = None - upload_options.cc = None - upload_options.message = None - upload_options.issue = None - upload_options.download_base = False - upload_options.send_mail = False - upload_options.vcs = None - upload_options.server = server - upload_options.save_cookies = True - - if testing: - upload_options.save_cookies = False - upload_options.email = "test@example.com" - - rpc = None - - global releaseBranch - tags = repo.branchmap().keys() - if 'release-branch.go10' in tags: - # NOTE(rsc): This tags.sort is going to get the wrong - # answer when comparing release-branch.go9 with - # release-branch.go10. It will be a while before we care. - raise hg_util.Abort('tags.sort needs to be fixed for release-branch.go10') - tags.sort() - for t in tags: - if t.startswith('release-branch.go'): - releaseBranch = t - -def workbranch(name): - return name == "default" or name.startswith('dev.') - -####################################################################### -# http://codereview.appspot.com/static/upload.py, heavily edited. - -#!/usr/bin/env python -# -# Copyright 2007 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tool for uploading diffs from a version control system to the codereview app. - -Usage summary: upload.py [options] [-- diff_options] - -Diff options are passed to the diff command of the underlying system. - -Supported version control systems: - Git - Mercurial - Subversion - -It is important for Git/Mercurial users to specify a tree/node/branch to diff -against by using the '--rev' option. -""" -# This code is derived from appcfg.py in the App Engine SDK (open source), -# and from ASPN recipe #146306. - -import cookielib -import getpass -import logging -import mimetypes -import optparse -import os -import re -import socket -import subprocess -import sys -import urllib -import urllib2 -import urlparse - -# The md5 module was deprecated in Python 2.5. -try: - from hashlib import md5 -except ImportError: - from md5 import md5 - -try: - import readline -except ImportError: - pass - -# The logging verbosity: -# 0: Errors only. -# 1: Status messages. -# 2: Info logs. -# 3: Debug logs. -verbosity = 1 - -# Max size of patch or base file. -MAX_UPLOAD_SIZE = 900 * 1024 - -# whitelist for non-binary filetypes which do not start with "text/" -# .mm (Objective-C) shows up as application/x-freemind on my Linux box. -TEXT_MIMETYPES = [ - 'application/javascript', - 'application/x-javascript', - 'application/x-freemind' -] - -def GetEmail(prompt): - """Prompts the user for their email address and returns it. - - The last used email address is saved to a file and offered up as a suggestion - to the user. If the user presses enter without typing in anything the last - used email address is used. If the user enters a new address, it is saved - for next time we prompt. - - """ - last_email_file_name = os.path.expanduser("~/.last_codereview_email_address") - last_email = "" - if os.path.exists(last_email_file_name): - try: - last_email_file = open(last_email_file_name, "r") - last_email = last_email_file.readline().strip("\n") - last_email_file.close() - prompt += " [%s]" % last_email - except IOError, e: - pass - email = raw_input(prompt + ": ").strip() - if email: - try: - last_email_file = open(last_email_file_name, "w") - last_email_file.write(email) - last_email_file.close() - except IOError, e: - pass - else: - email = last_email - return email - - -def StatusUpdate(msg): - """Print a status message to stdout. - - If 'verbosity' is greater than 0, print the message. - - Args: - msg: The string to print. - """ - if verbosity > 0: - print msg - - -def ErrorExit(msg): - """Print an error message to stderr and exit.""" - print >>sys.stderr, msg - sys.exit(1) - - -class ClientLoginError(urllib2.HTTPError): - """Raised to indicate there was an error authenticating with ClientLogin.""" - - def __init__(self, url, code, msg, headers, args): - urllib2.HTTPError.__init__(self, url, code, msg, headers, None) - self.args = args - # .reason is now a read-only property based on .msg - # this means we ignore 'msg', but that seems to work fine. - self.msg = args["Error"] - - -class AbstractRpcServer(object): - """Provides a common interface for a simple RPC server.""" - - def __init__(self, host, auth_function, host_override=None, extra_headers={}, save_cookies=False): - """Creates a new HttpRpcServer. - - Args: - host: The host to send requests to. - auth_function: A function that takes no arguments and returns an - (email, password) tuple when called. Will be called if authentication - is required. - host_override: The host header to send to the server (defaults to host). - extra_headers: A dict of extra headers to append to every request. - save_cookies: If True, save the authentication cookies to local disk. - If False, use an in-memory cookiejar instead. Subclasses must - implement this functionality. Defaults to False. - """ - self.host = host - self.host_override = host_override - self.auth_function = auth_function - self.authenticated = False - self.extra_headers = extra_headers - self.save_cookies = save_cookies - self.opener = self._GetOpener() - if self.host_override: - logging.info("Server: %s; Host: %s", self.host, self.host_override) - else: - logging.info("Server: %s", self.host) - - def _GetOpener(self): - """Returns an OpenerDirector for making HTTP requests. - - Returns: - A urllib2.OpenerDirector object. - """ - raise NotImplementedError() - - def _CreateRequest(self, url, data=None): - """Creates a new urllib request.""" - logging.debug("Creating request for: '%s' with payload:\n%s", url, data) - req = urllib2.Request(url, data=data) - if self.host_override: - req.add_header("Host", self.host_override) - for key, value in self.extra_headers.iteritems(): - req.add_header(key, value) - return req - - def _GetAuthToken(self, email, password): - """Uses ClientLogin to authenticate the user, returning an auth token. - - Args: - email: The user's email address - password: The user's password - - Raises: - ClientLoginError: If there was an error authenticating with ClientLogin. - HTTPError: If there was some other form of HTTP error. - - Returns: - The authentication token returned by ClientLogin. - """ - account_type = "GOOGLE" - if self.host.endswith(".google.com") and not force_google_account: - # Needed for use inside Google. - account_type = "HOSTED" - req = self._CreateRequest( - url="https://www.google.com/accounts/ClientLogin", - data=urllib.urlencode({ - "Email": email, - "Passwd": password, - "service": "ah", - "source": "rietveld-codereview-upload", - "accountType": account_type, - }), - ) - try: - response = self.opener.open(req) - response_body = response.read() - response_dict = dict(x.split("=") for x in response_body.split("\n") if x) - return response_dict["Auth"] - except urllib2.HTTPError, e: - if e.code == 403: - body = e.read() - response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) - raise ClientLoginError(req.get_full_url(), e.code, e.msg, e.headers, response_dict) - else: - raise - - def _GetAuthCookie(self, auth_token): - """Fetches authentication cookies for an authentication token. - - Args: - auth_token: The authentication token returned by ClientLogin. - - Raises: - HTTPError: If there was an error fetching the authentication cookies. - """ - # This is a dummy value to allow us to identify when we're successful. - continue_location = "http://localhost/" - args = {"continue": continue_location, "auth": auth_token} - reqUrl = "https://%s/_ah/login?%s" % (self.host, urllib.urlencode(args)) - if testing: - reqUrl = reqUrl.replace("https://", "http://") - req = self._CreateRequest(reqUrl) - try: - response = self.opener.open(req) - except urllib2.HTTPError, e: - response = e - if (response.code != 302 or - response.info()["location"] != continue_location): - raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp) - self.authenticated = True - - def _Authenticate(self): - """Authenticates the user. - - The authentication process works as follows: - 1) We get a username and password from the user - 2) We use ClientLogin to obtain an AUTH token for the user - (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). - 3) We pass the auth token to /_ah/login on the server to obtain an - authentication cookie. If login was successful, it tries to redirect - us to the URL we provided. - - If we attempt to access the upload API without first obtaining an - authentication cookie, it returns a 401 response (or a 302) and - directs us to authenticate ourselves with ClientLogin. - """ - for i in range(3): - credentials = self.auth_function() - try: - auth_token = self._GetAuthToken(credentials[0], credentials[1]) - except ClientLoginError, e: - if e.msg == "BadAuthentication": - print >>sys.stderr, "Invalid username or password." - continue - if e.msg == "CaptchaRequired": - print >>sys.stderr, ( - "Please go to\n" - "https://www.google.com/accounts/DisplayUnlockCaptcha\n" - "and verify you are a human. Then try again.") - break - if e.msg == "NotVerified": - print >>sys.stderr, "Account not verified." - break - if e.msg == "TermsNotAgreed": - print >>sys.stderr, "User has not agreed to TOS." - break - if e.msg == "AccountDeleted": - print >>sys.stderr, "The user account has been deleted." - break - if e.msg == "AccountDisabled": - print >>sys.stderr, "The user account has been disabled." - break - if e.msg == "ServiceDisabled": - print >>sys.stderr, "The user's access to the service has been disabled." - break - if e.msg == "ServiceUnavailable": - print >>sys.stderr, "The service is not available; try again later." - break - raise - self._GetAuthCookie(auth_token) - return - - def Send(self, request_path, payload=None, - content_type="application/octet-stream", - timeout=None, - **kwargs): - """Sends an RPC and returns the response. - - Args: - request_path: The path to send the request to, eg /api/appversion/create. - payload: The body of the request, or None to send an empty request. - content_type: The Content-Type header to use. - timeout: timeout in seconds; default None i.e. no timeout. - (Note: for large requests on OS X, the timeout doesn't work right.) - kwargs: Any keyword arguments are converted into query string parameters. - - Returns: - The response body, as a string. - """ - # TODO: Don't require authentication. Let the server say - # whether it is necessary. - if not self.authenticated: - self._Authenticate() - - old_timeout = socket.getdefaulttimeout() - socket.setdefaulttimeout(timeout) - try: - tries = 0 - while True: - tries += 1 - args = dict(kwargs) - url = "https://%s%s" % (self.host, request_path) - if testing: - url = url.replace("https://", "http://") - if args: - url += "?" + urllib.urlencode(args) - req = self._CreateRequest(url=url, data=payload) - req.add_header("Content-Type", content_type) - try: - f = self.opener.open(req) - response = f.read() - f.close() - return response - except urllib2.HTTPError, e: - if tries > 3: - raise - elif e.code == 401 or e.code == 302: - self._Authenticate() - else: - raise - finally: - socket.setdefaulttimeout(old_timeout) - - -class HttpRpcServer(AbstractRpcServer): - """Provides a simplified RPC-style interface for HTTP requests.""" - - def _Authenticate(self): - """Save the cookie jar after authentication.""" - super(HttpRpcServer, self)._Authenticate() - if self.save_cookies: - StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) - self.cookie_jar.save() - - def _GetOpener(self): - """Returns an OpenerDirector that supports cookies and ignores redirects. - - Returns: - A urllib2.OpenerDirector object. - """ - opener = urllib2.OpenerDirector() - opener.add_handler(urllib2.ProxyHandler()) - opener.add_handler(urllib2.UnknownHandler()) - opener.add_handler(urllib2.HTTPHandler()) - opener.add_handler(urllib2.HTTPDefaultErrorHandler()) - opener.add_handler(urllib2.HTTPSHandler()) - opener.add_handler(urllib2.HTTPErrorProcessor()) - if self.save_cookies: - self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies_" + server) - self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file) - if os.path.exists(self.cookie_file): - try: - self.cookie_jar.load() - self.authenticated = True - StatusUpdate("Loaded authentication cookies from %s" % self.cookie_file) - except (cookielib.LoadError, IOError): - # Failed to load cookies - just ignore them. - pass - else: - # Create an empty cookie file with mode 600 - fd = os.open(self.cookie_file, os.O_CREAT, 0600) - os.close(fd) - # Always chmod the cookie file - os.chmod(self.cookie_file, 0600) - else: - # Don't save cookies across runs of update.py. - self.cookie_jar = cookielib.CookieJar() - opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar)) - return opener - - -def GetRpcServer(options): - """Returns an instance of an AbstractRpcServer. - - Returns: - A new AbstractRpcServer, on which RPC calls can be made. - """ - - rpc_server_class = HttpRpcServer - - def GetUserCredentials(): - """Prompts the user for a username and password.""" - # Disable status prints so they don't obscure the password prompt. - global global_status - st = global_status - global_status = None - - email = options.email - if email is None: - email = GetEmail("Email (login for uploading to %s)" % options.server) - password = getpass.getpass("Password for %s: " % email) - - # Put status back. - global_status = st - return (email, password) - - # If this is the dev_appserver, use fake authentication. - host = (options.host or options.server).lower() - if host == "localhost" or host.startswith("localhost:"): - email = options.email - if email is None: - email = "test@example.com" - logging.info("Using debug user %s. Override with --email" % email) - server = rpc_server_class( - options.server, - lambda: (email, "password"), - host_override=options.host, - extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email}, - save_cookies=options.save_cookies) - # Don't try to talk to ClientLogin. - server.authenticated = True - return server - - return rpc_server_class(options.server, GetUserCredentials, - host_override=options.host, save_cookies=options.save_cookies) - - -def EncodeMultipartFormData(fields, files): - """Encode form fields for multipart/form-data. - - Args: - fields: A sequence of (name, value) elements for regular form fields. - files: A sequence of (name, filename, value) elements for data to be - uploaded as files. - Returns: - (content_type, body) ready for httplib.HTTP instance. - - Source: - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 - """ - BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' - CRLF = '\r\n' - lines = [] - for (key, value) in fields: - typecheck(key, str) - typecheck(value, str) - lines.append('--' + BOUNDARY) - lines.append('Content-Disposition: form-data; name="%s"' % key) - lines.append('') - lines.append(value) - for (key, filename, value) in files: - typecheck(key, str) - typecheck(filename, str) - typecheck(value, str) - lines.append('--' + BOUNDARY) - lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) - lines.append('Content-Type: %s' % GetContentType(filename)) - lines.append('') - lines.append(value) - lines.append('--' + BOUNDARY + '--') - lines.append('') - body = CRLF.join(lines) - content_type = 'multipart/form-data; boundary=%s' % BOUNDARY - return content_type, body - - -def GetContentType(filename): - """Helper to guess the content-type from the filename.""" - return mimetypes.guess_type(filename)[0] or 'application/octet-stream' - - -# Use a shell for subcommands on Windows to get a PATH search. -use_shell = sys.platform.startswith("win") - -def RunShellWithReturnCode(command, print_output=False, - universal_newlines=True, env=os.environ): - """Executes a command and returns the output from stdout and the return code. - - Args: - command: Command to execute. - print_output: If True, the output is printed to stdout. - If False, both stdout and stderr are ignored. - universal_newlines: Use universal_newlines flag (default: True). - - Returns: - Tuple (output, return code) - """ - logging.info("Running %s", command) - p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - shell=use_shell, universal_newlines=universal_newlines, env=env) - if print_output: - output_array = [] - while True: - line = p.stdout.readline() - if not line: - break - print line.strip("\n") - output_array.append(line) - output = "".join(output_array) - else: - output = p.stdout.read() - p.wait() - errout = p.stderr.read() - if print_output and errout: - print >>sys.stderr, errout - p.stdout.close() - p.stderr.close() - return output, p.returncode - - -def RunShell(command, silent_ok=False, universal_newlines=True, - print_output=False, env=os.environ): - data, retcode = RunShellWithReturnCode(command, print_output, universal_newlines, env) - if retcode: - ErrorExit("Got error status from %s:\n%s" % (command, data)) - if not silent_ok and not data: - ErrorExit("No output from %s" % command) - return data - - -class VersionControlSystem(object): - """Abstract base class providing an interface to the VCS.""" - - def __init__(self, options): - """Constructor. - - Args: - options: Command line options. - """ - self.options = options - - def GenerateDiff(self, args): - """Return the current diff as a string. - - Args: - args: Extra arguments to pass to the diff command. - """ - raise NotImplementedError( - "abstract method -- subclass %s must override" % self.__class__) - - def GetUnknownFiles(self): - """Return a list of files unknown to the VCS.""" - raise NotImplementedError( - "abstract method -- subclass %s must override" % self.__class__) - - def CheckForUnknownFiles(self): - """Show an "are you sure?" prompt if there are unknown files.""" - unknown_files = self.GetUnknownFiles() - if unknown_files: - print "The following files are not added to version control:" - for line in unknown_files: - print line - prompt = "Are you sure to continue?(y/N) " - answer = raw_input(prompt).strip() - if answer != "y": - ErrorExit("User aborted") - - def GetBaseFile(self, filename): - """Get the content of the upstream version of a file. - - Returns: - A tuple (base_content, new_content, is_binary, status) - base_content: The contents of the base file. - new_content: For text files, this is empty. For binary files, this is - the contents of the new file, since the diff output won't contain - information to reconstruct the current file. - is_binary: True iff the file is binary. - status: The status of the file. - """ - - raise NotImplementedError( - "abstract method -- subclass %s must override" % self.__class__) - - - def GetBaseFiles(self, diff): - """Helper that calls GetBase file for each file in the patch. - - Returns: - A dictionary that maps from filename to GetBaseFile's tuple. Filenames - are retrieved based on lines that start with "Index:" or - "Property changes on:". - """ - files = {} - for line in diff.splitlines(True): - if line.startswith('Index:') or line.startswith('Property changes on:'): - unused, filename = line.split(':', 1) - # On Windows if a file has property changes its filename uses '\' - # instead of '/'. - filename = to_slash(filename.strip()) - files[filename] = self.GetBaseFile(filename) - return files - - - def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, - files): - """Uploads the base files (and if necessary, the current ones as well).""" - - def UploadFile(filename, file_id, content, is_binary, status, is_base): - """Uploads a file to the server.""" - set_status("uploading " + filename) - file_too_large = False - if is_base: - type = "base" - else: - type = "current" - if len(content) > MAX_UPLOAD_SIZE: - print ("Not uploading the %s file for %s because it's too large." % - (type, filename)) - file_too_large = True - content = "" - checksum = md5(content).hexdigest() - if options.verbose > 0 and not file_too_large: - print "Uploading %s file for %s" % (type, filename) - url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id) - form_fields = [ - ("filename", filename), - ("status", status), - ("checksum", checksum), - ("is_binary", str(is_binary)), - ("is_current", str(not is_base)), - ] - if file_too_large: - form_fields.append(("file_too_large", "1")) - if options.email: - form_fields.append(("user", options.email)) - ctype, body = EncodeMultipartFormData(form_fields, [("data", filename, content)]) - response_body = rpc_server.Send(url, body, content_type=ctype) - if not response_body.startswith("OK"): - StatusUpdate(" --> %s" % response_body) - sys.exit(1) - - # Don't want to spawn too many threads, nor do we want to - # hit Rietveld too hard, or it will start serving 500 errors. - # When 8 works, it's no better than 4, and sometimes 8 is - # too many for Rietveld to handle. - MAX_PARALLEL_UPLOADS = 4 - - sema = threading.BoundedSemaphore(MAX_PARALLEL_UPLOADS) - upload_threads = [] - finished_upload_threads = [] - - class UploadFileThread(threading.Thread): - def __init__(self, args): - threading.Thread.__init__(self) - self.args = args - def run(self): - UploadFile(*self.args) - finished_upload_threads.append(self) - sema.release() - - def StartUploadFile(*args): - sema.acquire() - while len(finished_upload_threads) > 0: - t = finished_upload_threads.pop() - upload_threads.remove(t) - t.join() - t = UploadFileThread(args) - upload_threads.append(t) - t.start() - - def WaitForUploads(): - for t in upload_threads: - t.join() - - patches = dict() - [patches.setdefault(v, k) for k, v in patch_list] - for filename in patches.keys(): - base_content, new_content, is_binary, status = files[filename] - file_id_str = patches.get(filename) - if file_id_str.find("nobase") != -1: - base_content = None - file_id_str = file_id_str[file_id_str.rfind("_") + 1:] - file_id = int(file_id_str) - if base_content != None: - StartUploadFile(filename, file_id, base_content, is_binary, status, True) - if new_content != None: - StartUploadFile(filename, file_id, new_content, is_binary, status, False) - WaitForUploads() - - def IsImage(self, filename): - """Returns true if the filename has an image extension.""" - mimetype = mimetypes.guess_type(filename)[0] - if not mimetype: - return False - return mimetype.startswith("image/") - - def IsBinary(self, filename): - """Returns true if the guessed mimetyped isnt't in text group.""" - mimetype = mimetypes.guess_type(filename)[0] - if not mimetype: - return False # e.g. README, "real" binaries usually have an extension - # special case for text files which don't start with text/ - if mimetype in TEXT_MIMETYPES: - return False - return not mimetype.startswith("text/") - - -class FakeMercurialUI(object): - def __init__(self): - self.quiet = True - self.output = '' - self.debugflag = False - - def write(self, *args, **opts): - self.output += ' '.join(args) - def copy(self): - return self - def status(self, *args, **opts): - pass - - def formatter(self, topic, opts): - from mercurial.formatter import plainformatter - return plainformatter(self, topic, opts) - - def readconfig(self, *args, **opts): - pass - def expandpath(self, *args, **opts): - return global_ui.expandpath(*args, **opts) - def configitems(self, *args, **opts): - return global_ui.configitems(*args, **opts) - def config(self, *args, **opts): - return global_ui.config(*args, **opts) - -use_hg_shell = False # set to True to shell out to hg always; slower - -class MercurialVCS(VersionControlSystem): - """Implementation of the VersionControlSystem interface for Mercurial.""" - - def __init__(self, options, ui, repo): - super(MercurialVCS, self).__init__(options) - self.ui = ui - self.repo = repo - self.status = None - # Absolute path to repository (we can be in a subdir) - self.repo_dir = os.path.normpath(repo.root) - # Compute the subdir - cwd = os.path.normpath(os.getcwd()) - assert cwd.startswith(self.repo_dir) - self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/") - mqparent, err = RunShellWithReturnCode(['hg', 'log', '--rev', 'qparent', '--template={node}']) - if not err and mqparent != "": - self.base_rev = mqparent - else: - out = RunShell(["hg", "parents", "-q", "--template={node} {branch}"], silent_ok=True).strip() - if not out: - # No revisions; use 0 to mean a repository with nothing. - out = "0:0 default" - - # Find parent along current branch. - branch = repo[None].branch() - base = "" - for line in out.splitlines(): - fields = line.strip().split(' ') - if fields[1] == branch: - base = fields[0] - break - if base == "": - # Use the first parent - base = out.strip().split(' ')[0] - self.base_rev = base - - def _GetRelPath(self, filename): - """Get relative path of a file according to the current directory, - given its logical path in the repo.""" - assert filename.startswith(self.subdir), (filename, self.subdir) - return filename[len(self.subdir):].lstrip(r"\/") - - def GenerateDiff(self, extra_args): - # If no file specified, restrict to the current subdir - extra_args = extra_args or ["."] - cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args - data = RunShell(cmd, silent_ok=True) - svndiff = [] - filecount = 0 - for line in data.splitlines(): - m = re.match("diff --git a/(\S+) b/(\S+)", line) - if m: - # Modify line to make it look like as it comes from svn diff. - # With this modification no changes on the server side are required - # to make upload.py work with Mercurial repos. - # NOTE: for proper handling of moved/copied files, we have to use - # the second filename. - filename = m.group(2) - svndiff.append("Index: %s" % filename) - svndiff.append("=" * 67) - filecount += 1 - logging.info(line) - else: - svndiff.append(line) - if not filecount: - ErrorExit("No valid patches found in output from hg diff") - return "\n".join(svndiff) + "\n" - - def GetUnknownFiles(self): - """Return a list of files unknown to the VCS.""" - args = [] - status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."], - silent_ok=True) - unknown_files = [] - for line in status.splitlines(): - st, fn = line.split(" ", 1) - if st == "?": - unknown_files.append(fn) - return unknown_files - - def get_hg_status(self, rev, path): - # We'd like to use 'hg status -C path', but that is buggy - # (see http://mercurial.selenic.com/bts/issue3023). - # Instead, run 'hg status -C' without a path - # and skim the output for the path we want. - if self.status is None: - if use_hg_shell: - out = RunShell(["hg", "status", "-C", "--rev", rev]) - else: - fui = FakeMercurialUI() - ret = hg_commands.status(fui, self.repo, *[], **{'rev': [rev], 'copies': True}) - if ret: - raise hg_util.Abort(ret) - out = fui.output - self.status = out.splitlines() - for i in range(len(self.status)): - # line is - # A path - # M path - # etc - line = to_slash(self.status[i]) - if line[2:] == path: - if i+1 < len(self.status) and self.status[i+1][:2] == ' ': - return self.status[i:i+2] - return self.status[i:i+1] - raise hg_util.Abort("no status for " + path) - - def GetBaseFile(self, filename): - set_status("inspecting " + filename) - # "hg status" and "hg cat" both take a path relative to the current subdir - # rather than to the repo root, but "hg diff" has given us the full path - # to the repo root. - base_content = "" - new_content = None - is_binary = False - oldrelpath = relpath = self._GetRelPath(filename) - out = self.get_hg_status(self.base_rev, relpath) - status, what = out[0].split(' ', 1) - if len(out) > 1 and status == "A" and what == relpath: - oldrelpath = out[1].strip() - status = "M" - if ":" in self.base_rev: - base_rev = self.base_rev.split(":", 1)[0] - else: - base_rev = self.base_rev - if status != "A": - if use_hg_shell: - base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath], silent_ok=True) - else: - try: - base_content = str(self.repo[base_rev][oldrelpath].data()) - except Exception: - pass - is_binary = "\0" in base_content # Mercurial's heuristic - if status != "R": - try: - new_content = open(relpath, "rb").read() - is_binary = is_binary or "\0" in new_content - except Exception: - pass - if is_binary and base_content and use_hg_shell: - # Fetch again without converting newlines - base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath], - silent_ok=True, universal_newlines=False) - if not is_binary or not self.IsImage(relpath): - new_content = None - return base_content, new_content, is_binary, status - - -# NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync. -def SplitPatch(data): - """Splits a patch into separate pieces for each file. - - Args: - data: A string containing the output of svn diff. - - Returns: - A list of 2-tuple (filename, text) where text is the svn diff output - pertaining to filename. - """ - patches = [] - filename = None - diff = [] - for line in data.splitlines(True): - new_filename = None - if line.startswith('Index:'): - unused, new_filename = line.split(':', 1) - new_filename = new_filename.strip() - elif line.startswith('Property changes on:'): - unused, temp_filename = line.split(':', 1) - # When a file is modified, paths use '/' between directories, however - # when a property is modified '\' is used on Windows. Make them the same - # otherwise the file shows up twice. - temp_filename = to_slash(temp_filename.strip()) - if temp_filename != filename: - # File has property changes but no modifications, create a new diff. - new_filename = temp_filename - if new_filename: - if filename and diff: - patches.append((filename, ''.join(diff))) - filename = new_filename - diff = [line] - continue - if diff is not None: - diff.append(line) - if filename and diff: - patches.append((filename, ''.join(diff))) - return patches - - -def UploadSeparatePatches(issue, rpc_server, patchset, data, options): - """Uploads a separate patch for each file in the diff output. - - Returns a list of [patch_key, filename] for each file. - """ - patches = SplitPatch(data) - rv = [] - for patch in patches: - set_status("uploading patch for " + patch[0]) - if len(patch[1]) > MAX_UPLOAD_SIZE: - print ("Not uploading the patch for " + patch[0] + - " because the file is too large.") - continue - form_fields = [("filename", patch[0])] - if not options.download_base: - form_fields.append(("content_upload", "1")) - files = [("data", "data.diff", patch[1])] - ctype, body = EncodeMultipartFormData(form_fields, files) - url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) - print "Uploading patch for " + patch[0] - response_body = rpc_server.Send(url, body, content_type=ctype) - lines = response_body.splitlines() - if not lines or lines[0] != "OK": - StatusUpdate(" --> %s" % response_body) - sys.exit(1) - rv.append([lines[1], patch[0]]) - return rv diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/.hgignore b/Godeps/_workspace/src/github.com/alexbrainman/odbc/.hgignore similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/.hgignore rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/.hgignore diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/AUTHORS b/Godeps/_workspace/src/github.com/alexbrainman/odbc/AUTHORS similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/AUTHORS rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/AUTHORS diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/CONTRIBUTORS b/Godeps/_workspace/src/github.com/alexbrainman/odbc/CONTRIBUTORS similarity index 94% rename from Godeps/_workspace/src/code.google.com/p/odbc/CONTRIBUTORS rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/CONTRIBUTORS index dad0ebb..778a94d 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/CONTRIBUTORS +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/CONTRIBUTORS @@ -33,4 +33,5 @@ Alex Brainman Andrew Gerrand +Chris Hines Luke Mauldin diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/LICENSE b/Godeps/_workspace/src/github.com/alexbrainman/odbc/LICENSE similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/LICENSE rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/LICENSE diff --git a/Godeps/_workspace/src/github.com/alexbrainman/odbc/README.md b/Godeps/_workspace/src/github.com/alexbrainman/odbc/README.md new file mode 100644 index 0000000..ffbb04f --- /dev/null +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/README.md @@ -0,0 +1,3 @@ +odbc driver written in go. Implements database driver interface as used by standard database/sql package. It calls into odbc dll on Windows, and uses cgo (unixODBC) everywhere else. + +To get started using odbc, have a look at the [wiki](../../wiki) pages. diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/api/Makefile b/Godeps/_workspace/src/github.com/alexbrainman/odbc/api/Makefile similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/api/Makefile rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/api/Makefile diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/api/api.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/api/api.go similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/api/api.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/api/api.go diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/api/api_unix.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/api/api_unix.go similarity index 98% rename from Godeps/_workspace/src/code.google.com/p/odbc/api/api_unix.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/api/api_unix.go index 260aa6b..adad06b 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/api/api_unix.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/api/api_unix.go @@ -7,8 +7,8 @@ package api -// #cgo darwin LDFLAGS: -lodbc -L/opt/local/lib -// #cgo darwin CFLAGS: -I/opt/local/include +// #cgo darwin LDFLAGS: -lodbc -L/usr/local/lib +// #cgo darwin CFLAGS: -I/usr/local/include // #cgo linux LDFLAGS: -lodbc // #include // #include diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/api/api_windows.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/api/api_windows.go similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/api/api_windows.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/api/api_windows.go diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/api/api_windows_386.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/api/api_windows_386.go similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/api/api_windows_386.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/api/api_windows_386.go diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/api/api_windows_amd64.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/api/api_windows_amd64.go similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/api/api_windows_amd64.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/api/api_windows_amd64.go diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/api/mksyscall_unix.pl b/Godeps/_workspace/src/github.com/alexbrainman/odbc/api/mksyscall_unix.pl similarity index 96% rename from Godeps/_workspace/src/code.google.com/p/odbc/api/mksyscall_unix.pl rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/api/mksyscall_unix.pl index 3abe529..4480284 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/api/mksyscall_unix.pl +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/api/mksyscall_unix.pl @@ -121,8 +121,8 @@ package $package import "unsafe" -// #cgo darwin LDFLAGS: -lodbc -L/opt/local/lib -// #cgo darwin CFLAGS: -I/opt/local/include +// #cgo darwin LDFLAGS: -lodbc -L/usr/local/lib +// #cgo darwin CFLAGS: -I/usr/local/include // #cgo linux LDFLAGS: -lodbc // #include // #include diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/api/zapi_unix.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/api/zapi_unix.go similarity index 98% rename from Godeps/_workspace/src/code.google.com/p/odbc/api/zapi_unix.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/api/zapi_unix.go index d127a54..2d076ce 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/api/zapi_unix.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/api/zapi_unix.go @@ -12,8 +12,8 @@ package api import "unsafe" -// #cgo darwin LDFLAGS: -lodbc -L/opt/local/lib -// #cgo darwin CFLAGS: -I/opt/local/include +// #cgo darwin LDFLAGS: -lodbc -L/usr/local/lib +// #cgo darwin CFLAGS: -I/usr/local/include // #cgo linux LDFLAGS: -lodbc // #include // #include diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/api/zapi_windows.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/api/zapi_windows.go similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/api/zapi_windows.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/api/zapi_windows.go diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/column.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/column.go similarity index 99% rename from Godeps/_workspace/src/code.google.com/p/odbc/column.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/column.go index de06703..fcc5a3c 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/column.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/column.go @@ -5,12 +5,13 @@ package odbc import ( - "code.google.com/p/odbc/api" "database/sql/driver" "errors" "fmt" "time" "unsafe" + + "github.com/alexbrainman/odbc/api" ) type BufferLen api.SQLLEN diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/conn.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/conn.go similarity index 64% rename from Godeps/_workspace/src/code.google.com/p/odbc/conn.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/conn.go index bf3cd23..5569dec 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/conn.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/conn.go @@ -5,14 +5,16 @@ package odbc import ( - "code.google.com/p/odbc/api" "database/sql/driver" "unsafe" + + "github.com/alexbrainman/odbc/api" ) type Conn struct { - h api.SQLHDBC - tx *Tx + h api.SQLHDBC + tx *Tx + bad bool } func (d *Driver) Open(dsn string) (driver.Conn, error) { @@ -35,12 +37,29 @@ func (d *Driver) Open(dsn string) (driver.Conn, error) { return &Conn{h: h}, nil } -func (c *Conn) Close() error { +func (c *Conn) Close() (err error) { + if c.tx != nil { + c.tx.Rollback() + } + h := c.h + defer func() { + c.h = api.SQLHDBC(api.SQL_NULL_HDBC) + e := releaseHandle(h) + if err == nil { + err = e + } + }() ret := api.SQLDisconnect(c.h) if IsError(ret) { - return NewError("SQLDisconnect", c.h) + return c.newError("SQLDisconnect", h) } - h := c.h - c.h = api.SQLHDBC(api.SQL_NULL_HDBC) - return releaseHandle(h) + return err +} + +func (c *Conn) newError(apiName string, handle interface{}) error { + err := NewError(apiName, handle) + if err == driver.ErrBadConn { + c.bad = true + } + return err } diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/driver.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/driver.go similarity index 98% rename from Godeps/_workspace/src/code.google.com/p/odbc/driver.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/driver.go index 4057628..b9783fc 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/driver.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/driver.go @@ -7,8 +7,9 @@ package odbc import ( - "code.google.com/p/odbc/api" "database/sql" + + "github.com/alexbrainman/odbc/api" ) var drv Driver diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/error.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/error.go similarity index 92% rename from Godeps/_workspace/src/code.google.com/p/odbc/error.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/error.go index 5c8593f..325e9c1 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/error.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/error.go @@ -5,10 +5,12 @@ package odbc import ( - "code.google.com/p/odbc/api" + "database/sql/driver" "fmt" "strings" "unsafe" + + "github.com/alexbrainman/odbc/api" ) func IsError(ret api.SQLRETURN) bool { @@ -60,6 +62,9 @@ func NewError(apiName string, handle interface{}) error { NativeError: int(ne), Message: api.UTF16ToString(msg), } + if r.State == "08S01" { + return driver.ErrBadConn + } err.Diag = append(err.Diag, r) } return err diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/foxpro_test.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/foxpro_test.go similarity index 97% rename from Godeps/_workspace/src/code.google.com/p/odbc/foxpro_test.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/foxpro_test.go index 5fea96f..dab1af0 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/foxpro_test.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/foxpro_test.go @@ -5,12 +5,13 @@ package odbc_test import ( - _ "code.google.com/p/odbc" "database/sql" "flag" "fmt" "testing" "time" + + _ "github.com/alexbrainman/odbc" ) var ( @@ -26,6 +27,9 @@ func TestFoxPro(t *testing.T) { t.Fatal(err) } defer db.Close() + if err := db.Ping(); err != nil { + t.Skipf("skipping test: %v", err) + } type row struct { char string diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/handle.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/handle.go similarity index 96% rename from Godeps/_workspace/src/code.google.com/p/odbc/handle.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/handle.go index 9498d0c..e765833 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/handle.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/handle.go @@ -5,8 +5,9 @@ package odbc import ( - "code.google.com/p/odbc/api" "fmt" + + "github.com/alexbrainman/odbc/api" ) func ToHandleAndType(handle interface{}) (h api.SQLHANDLE, ht api.SQLSMALLINT) { diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/mssql_test.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/mssql_test.go similarity index 80% rename from Godeps/_workspace/src/code.google.com/p/odbc/mssql_test.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/mssql_test.go index ce3344a..f68cdfd 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/mssql_test.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/mssql_test.go @@ -7,17 +7,21 @@ package odbc import ( "bytes" "database/sql" + "database/sql/driver" "errors" "flag" "fmt" + "io" + "net" "runtime" "strconv" "strings" + "sync" "sync/atomic" "testing" "time" - "code.google.com/p/odbc/api" + "github.com/alexbrainman/odbc/api" ) var ( @@ -41,8 +45,10 @@ func isFreeTDS() bool { return *msdriver == "freetds" } -func mssqlConnect() (db *sql.DB, stmtCount int, err error) { - params := map[string]string{ +type connParams map[string]string + +func newConnParams() connParams { + params := connParams{ "driver": *msdriver, "server": *mssrv, "database": *msdb, @@ -61,15 +67,59 @@ func mssqlConnect() (db *sql.DB, stmtCount int, err error) { params["pwd"] = *mspass } } + a := strings.SplitN(params["server"], ",", -1) + if len(a) == 2 { + params["server"] = a[0] + params["port"] = a[1] + } + return params +} + +func (params connParams) getConnAddress() (string, error) { + port, ok := params["port"] + if !ok { + return "", errors.New("no port number provided.") + } + host, ok := params["server"] + if !ok { + return "", errors.New("no host name provided.") + } + return host + ":" + port, nil +} + +func (params connParams) updateConnAddress(address string) error { + a := strings.SplitN(address, ":", -1) + if len(a) != 2 { + fmt.Errorf("listen address must have 2 fields, but %d found", len(a)) + } + params["server"] = a[0] + params["port"] = a[1] + return nil +} + +func (params connParams) makeODBCConnectionString() string { + if port, ok := params["port"]; ok { + params["server"] += "," + port + delete(params, "port") + } var c string for n, v := range params { c += n + "=" + v + ";" } - db, err = sql.Open("odbc", c) + return c +} + +func mssqlConnectWithParams(params connParams) (db *sql.DB, stmtCount int, err error) { + db, err = sql.Open("odbc", params.makeODBCConnectionString()) if err != nil { return nil, 0, err } - return db, db.Driver().(*Driver).Stats.StmtCount, nil + stats := db.Driver().(*Driver).Stats + return db, stats.StmtCount, nil +} + +func mssqlConnect() (db *sql.DB, stmtCount int, err error) { + return mssqlConnectWithParams(newConnParams()) } func closeDB(t *testing.T, db *sql.DB, shouldStmtCount, ignoreIfStmtCount int) { @@ -171,7 +221,7 @@ func is2008OrLater(db *sql.DB) bool { } func exec(t *testing.T, db *sql.DB, query string) { - // TODO(brainman): make sure http://code.google.com/p/go/issues/detail?id=3678 is fixed + // TODO(brainman): make sure https://github.com/golang/go/issues/3678 is fixed //r, err := db.Exec(query, a...) s, err := db.Prepare(query) if err != nil { @@ -188,6 +238,33 @@ func exec(t *testing.T, db *sql.DB, query string) { } } +func driverExec(t *testing.T, dc driver.Conn, query string) { + st, err := dc.Prepare(query) + if err != nil { + t.Fatal(err) + } + defer func() { + if err := st.Close(); err != nil && t != nil { + t.Fatal(err) + } + }() + + r, err := st.Exec([]driver.Value{}) + if err != nil { + if t != nil { + t.Fatal(err) + } + return + } + _, err = r.RowsAffected() + if err != nil { + if t != nil { + t.Fatalf("r.RowsAffected(%q ...) failed: %v", query, err) + } + return + } +} + func TestMSSQLCreateInsertDelete(t *testing.T) { db, sc, err := mssqlConnect() if err != nil { @@ -758,7 +835,7 @@ func TestMSSQLStmtAndRows(t *testing.T) { defer r.Close() // TODO(brainman): dangling statement(s) bug reported - // http://code.google.com/p/go/issues/detail?id=3865 + // https://github.com/golang/go/issues/3865 err = s.Close() if err != nil { t.Fatal(err) @@ -787,7 +864,7 @@ func TestMSSQLStmtAndRows(t *testing.T) { t.Fatalf("invalid statement count: expected %v, is %v", sc, db.Driver().(*Driver).Stats.StmtCount) } - // no reource tracking past this point + // no resource tracking past this point func() { // test 1 Stmt and many Query's executed one after the other @@ -887,6 +964,8 @@ func TestMSSQLIssue5(t *testing.T) { if err != nil { t.Fatal(err) } + + const nworkers = 8 defer closeDB(t, db, sc, sc) db.Exec("drop table dbo.temp") @@ -925,7 +1004,6 @@ func TestMSSQLIssue5(t *testing.T) { return } - const nworkers = 8 waitch := make(chan struct{}) errch := make(chan error, nworkers) for i := 0; i < nworkers; i++ { @@ -979,7 +1057,7 @@ func TestMSSQLDeleteNonExistent(t *testing.T) { exec(t, db, "drop table dbo.temp") } -// https://code.google.com/p/odbc/issues/detail?id=14 +// https://github.com/alexbrainman/odbc/issues/14 func TestMSSQLDatetime2Param(t *testing.T) { db, sc, err := mssqlConnect() if err != nil { @@ -1011,7 +1089,7 @@ func TestMSSQLDatetime2Param(t *testing.T) { exec(t, db, "drop table dbo.temp") } -// https://code.google.com/p/odbc/issues/detail?id=19 +// https://github.com/alexbrainman/odbc/issues/19 func TestMSSQLMerge(t *testing.T) { db, sc, err := mssqlConnect() if err != nil { @@ -1077,7 +1155,7 @@ func TestMSSQLMerge(t *testing.T) { exec(t, db, "drop table dbo.temp") } -// https://code.google.com/p/odbc/issues/detail?id=20 +// https://github.com/alexbrainman/odbc/issues/20 func TestMSSQLSelectInt(t *testing.T) { db, sc, err := mssqlConnect() if err != nil { @@ -1095,7 +1173,7 @@ func TestMSSQLSelectInt(t *testing.T) { } } -// https://code.google.com/p/odbc/issues/detail?id=21 +// https://github.com/alexbrainman/odbc/issues/21 func TestMSSQLTextColumnParam(t *testing.T) { db, sc, err := mssqlConnect() if err != nil { @@ -1274,7 +1352,7 @@ func TestMSSQLRawBytes(t *testing.T) { exec(t, db, "drop table dbo.temp") } -// https://code.google.com/p/odbc/issues/detail?id=27 +// https://github.com/alexbrainman/odbc/issues/27 func TestMSSQLUTF16ToUTF8(t *testing.T) { s := []uint16{0x47, 0x75, 0x73, 0x74, 0x61, 0x66, 0x27, 0x73, 0x20, 0x4b, 0x6e, 0xe4, 0x63, 0x6b, 0x65, 0x62, 0x72, 0xf6, 0x64} if api.UTF16ToString(s) != string(utf16toutf8(s)) { @@ -1328,7 +1406,316 @@ func TestMSSQLSingleCharParam(t *testing.T) { if err != nil { t.Fatal(err) } - defer rows.Close() + rows.Close() + + exec(t, db, "drop table dbo.temp") +} + +type tcpProxy struct { + mu sync.Mutex + stopped bool + conns []net.Conn +} + +func (p *tcpProxy) run(ln net.Listener, remote string) { + for { + defer p.pause() + c1, err := ln.Accept() + if err != nil { + return + } + go func(c1 net.Conn) { + defer c1.Close() + + if p.paused() { + return + } + + p.addConn(c1) + + c2, err := net.Dial("tcp", remote) + if err != nil { + panic(err) + } + p.addConn(c2) + defer c2.Close() + + go func() { + io.Copy(c2, c1) + }() + io.Copy(c1, c2) + }(c1) + } +} + +func (p *tcpProxy) pause() { + p.mu.Lock() + defer p.mu.Unlock() + p.stopped = true + for _, c := range p.conns { + c.Close() + } + p.conns = p.conns[:0] +} + +func (p *tcpProxy) paused() bool { + p.mu.Lock() + defer p.mu.Unlock() + return p.stopped +} + +func (p *tcpProxy) addConn(c net.Conn) { + p.mu.Lock() + defer p.mu.Unlock() + p.conns = append(p.conns, c) +} + +func (p *tcpProxy) restart() { + p.mu.Lock() + defer p.mu.Unlock() + p.stopped = false +} + +func TestMSSQLReconnect(t *testing.T) { + params := newConnParams() + address, err := params.getConnAddress() + if err != nil { + t.Skipf("Skipping test: %v", err) + } + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + + err = params.updateConnAddress(ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + + proxy := new(tcpProxy) + go proxy.run(ln, address) + + db, sc, err := mssqlConnectWithParams(params) + if err != nil { + t.Fatal(err) + } + defer closeDB(t, db, sc, sc) + + testConn := func() error { + var n int64 + err := db.QueryRow("select count(*) from dbo.temp").Scan(&n) + if err != nil { + return err + } + if n != 1 { + return fmt.Errorf("unexpected return value: should=1, is=%v", n) + } + return nil + } + + db.Exec("drop table dbo.temp") + exec(t, db, `create table dbo.temp (name varchar(50))`) + exec(t, db, `insert into dbo.temp (name) values ('alex')`) + + err = testConn() + if err != nil { + t.Fatal(err) + } + + proxy.pause() + time.Sleep(100 * time.Millisecond) + + err = testConn() + if err == nil { + t.Fatal("database IO should fail, but succeeded") + } + + proxy.restart() + + err = testConn() + if err != nil { + t.Fatal(err) + } exec(t, db, "drop table dbo.temp") } + +func TestMSSQLMarkTxBadConn(t *testing.T) { + params := newConnParams() + + address, err := params.getConnAddress() + if err != nil { + t.Skipf("Skipping test: %v", err) + } + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + + err = params.updateConnAddress(ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + + proxy := new(tcpProxy) + go proxy.run(ln, address) + + testFn := func(endTx func(driver.Tx) error, nextFn func(driver.Conn) error) { + proxy.restart() + + cc, sc := drv.Stats.ConnCount, drv.Stats.StmtCount + defer func() { + if should, is := sc, drv.Stats.StmtCount; should != is { + t.Errorf("leaked statement, should=%d, is=%d", should, is) + } + if should, is := cc, drv.Stats.ConnCount; should != is { + t.Errorf("leaked connection, should=%d, is=%d", should, is) + } + }() + + dc, err := drv.Open(params.makeODBCConnectionString()) + if err != nil { + t.Fatal(err) + } + defer func() { + if err := dc.Close(); err != nil { + t.Fatal(err) + } + }() + + driverExec(nil, dc, "drop table dbo.temp") + driverExec(t, dc, `create table dbo.temp (name varchar(50))`) + + tx, err := dc.Begin() + if err != nil { + t.Fatal(err) + } + + driverExec(t, dc, `insert into dbo.temp (name) values ('alex')`) + + proxy.pause() + time.Sleep(100 * time.Millisecond) + + // the connection is broken, ending the transaction should fail + if err := endTx(tx); err == nil { + t.Fatal("unexpected success, expected error") + } + + // database/sql might return the broken driver.Conn to the pool in + // that case the next operation must fail. + if err := nextFn(dc); err == nil { + t.Fatal("unexpected success, expected error") + } + } + + beginFn := func(dc driver.Conn) error { + tx, err := dc.Begin() + if err != nil { + return err + } + tx.Rollback() + return nil + } + + prepareFn := func(dc driver.Conn) error { + st, err := dc.Prepare(`insert into dbo.temp (name) values ('alex')`) + if err != nil { + return err + } + st.Close() + return nil + } + + // Test all the permutations. + for _, endTx := range []func(driver.Tx) error{ + driver.Tx.Commit, + driver.Tx.Rollback, + } { + for _, nextFn := range []func(driver.Conn) error{ + beginFn, + prepareFn, + } { + testFn(endTx, nextFn) + } + } +} + +func TestMSSQLMarkBeginBadConn(t *testing.T) { + params := newConnParams() + + testFn := func(label string, nextFn func(driver.Conn) error) { + cc, sc := drv.Stats.ConnCount, drv.Stats.StmtCount + defer func() { + if should, is := sc, drv.Stats.StmtCount; should != is { + t.Errorf("leaked statement, should=%d, is=%d", should, is) + } + if should, is := cc, drv.Stats.ConnCount; should != is { + t.Errorf("leaked connection, should=%d, is=%d", should, is) + } + }() + + dc, err := drv.Open(params.makeODBCConnectionString()) + if err != nil { + t.Fatal(err) + } + defer func() { + if err := dc.Close(); err != nil { + t.Fatal(err) + } + }() + + driverExec(nil, dc, "drop table dbo.temp") + driverExec(t, dc, `create table dbo.temp (name varchar(50))`) + + // force an error starting a transaction + func() { + testBeginErr = errors.New("cannot start tx") + defer func() { testBeginErr = nil }() + + if _, err := dc.Begin(); err == nil { + t.Fatal("unexpected success, expected error") + } + }() + + // database/sql might return the broken driver.Conn to the pool. The + // next operation on the driver connection must return + // driver.ErrBadConn to prevent the bad connection from getting used + // again. + if should, is := driver.ErrBadConn, nextFn(dc); should != is { + t.Errorf("%s: should=\"%v\", is=\"%v\"", label, should, is) + } + } + + beginFn := func(dc driver.Conn) error { + tx, err := dc.Begin() + if err != nil { + return err + } + tx.Rollback() + return nil + } + + prepareFn := func(dc driver.Conn) error { + st, err := dc.Prepare(`insert into dbo.temp (name) values ('alex')`) + if err != nil { + return err + } + st.Close() + return nil + } + + // Test all the permutations. + for _, next := range []struct { + label string + fn func(driver.Conn) error + }{ + {"begin", beginFn}, + {"prepare", prepareFn}, + } { + testFn(next.label, next.fn) + } +} diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/odbcstmt.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/odbcstmt.go similarity index 96% rename from Godeps/_workspace/src/code.google.com/p/odbc/odbcstmt.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/odbcstmt.go index 1bc2bca..5e58339 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/odbcstmt.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/odbcstmt.go @@ -5,13 +5,14 @@ package odbc import ( - "code.google.com/p/odbc/api" "database/sql/driver" "errors" "fmt" "sync" "time" "unsafe" + + "github.com/alexbrainman/odbc/api" ) // TODO(brainman): see if I could use SQLExecDirect anywhere @@ -30,7 +31,7 @@ func (c *Conn) PrepareODBCStmt(query string) (*ODBCStmt, error) { var out api.SQLHANDLE ret := api.SQLAllocHandle(api.SQL_HANDLE_STMT, api.SQLHANDLE(c.h), &out) if IsError(ret) { - return nil, NewError("SQLAllocHandle", c.h) + return nil, c.newError("SQLAllocHandle", c.h) } h := api.SQLHSTMT(out) drv.Stats.updateHandleCount(api.SQL_HANDLE_STMT, 1) @@ -39,7 +40,7 @@ func (c *Conn) PrepareODBCStmt(query string) (*ODBCStmt, error) { ret = api.SQLPrepare(h, (*api.SQLWCHAR)(unsafe.Pointer(&b[0])), api.SQL_NTS) if IsError(ret) { defer releaseHandle(h) - return nil, NewError("SQLPrepare", h) + return nil, c.newError("SQLPrepare", h) } ps, err := ExtractParameters(h) if err != nil { diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/param.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/param.go similarity index 99% rename from Godeps/_workspace/src/code.google.com/p/odbc/param.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/param.go index c0152ec..fa3f0d2 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/param.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/param.go @@ -5,11 +5,12 @@ package odbc import ( - "code.google.com/p/odbc/api" "database/sql/driver" "fmt" "time" "unsafe" + + "github.com/alexbrainman/odbc/api" ) type Parameter struct { diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/result.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/result.go similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/result.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/result.go diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/rows.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/rows.go similarity index 95% rename from Godeps/_workspace/src/code.google.com/p/odbc/rows.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/rows.go index 40cc2ff..bcc80ef 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/rows.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/rows.go @@ -5,9 +5,10 @@ package odbc import ( - "code.google.com/p/odbc/api" "database/sql/driver" "io" + + "github.com/alexbrainman/odbc/api" ) type Rows struct { diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/stats.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/stats.go similarity index 94% rename from Godeps/_workspace/src/code.google.com/p/odbc/stats.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/stats.go index bb3f24a..cbeb349 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/stats.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/stats.go @@ -5,9 +5,10 @@ package odbc import ( - "code.google.com/p/odbc/api" "fmt" "sync" + + "github.com/alexbrainman/odbc/api" ) type Stats struct { diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/stmt.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/stmt.go similarity index 95% rename from Godeps/_workspace/src/code.google.com/p/odbc/stmt.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/stmt.go index 670163d..2478aaa 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/stmt.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/stmt.go @@ -5,10 +5,11 @@ package odbc import ( - "code.google.com/p/odbc/api" "database/sql/driver" "errors" "sync" + + "github.com/alexbrainman/odbc/api" ) type Stmt struct { @@ -19,6 +20,9 @@ type Stmt struct { } func (c *Conn) Prepare(query string) (driver.Stmt, error) { + if c.bad { + return nil, driver.ErrBadConn + } os, err := c.PrepareODBCStmt(query) if err != nil { return nil, err diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/testdata/fldtest.dbf b/Godeps/_workspace/src/github.com/alexbrainman/odbc/testdata/fldtest.dbf similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/testdata/fldtest.dbf rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/testdata/fldtest.dbf diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/testdata/fldtest.fpt b/Godeps/_workspace/src/github.com/alexbrainman/odbc/testdata/fldtest.fpt similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/testdata/fldtest.fpt rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/testdata/fldtest.fpt diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/tx.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/tx.go similarity index 77% rename from Godeps/_workspace/src/code.google.com/p/odbc/tx.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/tx.go index c04d1d0..d7dc0f7 100644 --- a/Godeps/_workspace/src/code.google.com/p/odbc/tx.go +++ b/Godeps/_workspace/src/github.com/alexbrainman/odbc/tx.go @@ -5,31 +5,40 @@ package odbc import ( - "code.google.com/p/odbc/api" "database/sql/driver" "errors" + + "github.com/alexbrainman/odbc/api" ) type Tx struct { c *Conn } +var testBeginErr error // used during tests + func (c *Conn) setAutoCommitAttr(a uintptr) error { - ret := api.SQLSetConnectUIntPtrAttr(c.h, api.SQL_ATTR_AUTOCOMMIT, - a, api.SQL_IS_UINTEGER) + if testBeginErr != nil { + return testBeginErr + } + ret := api.SQLSetConnectUIntPtrAttr(c.h, api.SQL_ATTR_AUTOCOMMIT, a, api.SQL_IS_UINTEGER) if IsError(ret) { - return NewError("SQLSetConnectUIntPtrAttr", c.h) + return c.newError("SQLSetConnectUIntPtrAttr", c.h) } return nil } func (c *Conn) Begin() (driver.Tx, error) { + if c.bad { + return nil, driver.ErrBadConn + } if c.tx != nil { return nil, errors.New("already in a transaction") } c.tx = &Tx{c: c} err := c.setAutoCommitAttr(api.SQL_AUTOCOMMIT_OFF) if err != nil { + c.bad = true return nil, err } return c.tx, nil @@ -39,7 +48,6 @@ func (c *Conn) endTx(commit bool) error { if c.tx == nil { return errors.New("not in a transaction") } - c.tx = nil var howToEnd api.SQLSMALLINT if commit { howToEnd = api.SQL_COMMIT @@ -48,10 +56,13 @@ func (c *Conn) endTx(commit bool) error { } ret := api.SQLEndTran(api.SQL_HANDLE_DBC, api.SQLHANDLE(c.h), howToEnd) if IsError(ret) { - return NewError("SQLEndTran", c.h) + c.bad = true + return c.newError("SQLEndTran", c.h) } + c.tx = nil err := c.setAutoCommitAttr(api.SQL_AUTOCOMMIT_ON) if err != nil { + c.bad = true return err } return nil diff --git a/Godeps/_workspace/src/code.google.com/p/odbc/utf16.go b/Godeps/_workspace/src/github.com/alexbrainman/odbc/utf16.go similarity index 100% rename from Godeps/_workspace/src/code.google.com/p/odbc/utf16.go rename to Godeps/_workspace/src/github.com/alexbrainman/odbc/utf16.go diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/.gitignore b/Godeps/_workspace/src/github.com/onsi/ginkgo/.gitignore deleted file mode 100644 index 922b4f7..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.DS_Store -TODO -tmp/**/* -*.coverprofile \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/.travis.yml b/Godeps/_workspace/src/github.com/onsi/ginkgo/.travis.yml deleted file mode 100644 index f8b6984..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go -go: - - 1.4 - -install: - - go get -v ./... - - go get golang.org/x/tools/cmd/cover - - go get github.com/onsi/gomega - - go install github.com/onsi/ginkgo/ginkgo - - export PATH=$PATH:$HOME/gopath/bin - -script: $HOME/gopath/bin/ginkgo -r --randomizeAllSpecs --failOnPending --randomizeSuites --race diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/CHANGELOG.md b/Godeps/_workspace/src/github.com/onsi/ginkgo/CHANGELOG.md deleted file mode 100644 index 6bed618..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/CHANGELOG.md +++ /dev/null @@ -1,123 +0,0 @@ -## HEAD - -Improvements - -- `ginkgo -coverpkg` calls down to `go test -coverpkg` (#160) - -## 1.2.0-beta - -Ginkgo now requires Go 1.4+ - -Improvements: - -- Call reporters in reverse order when announcing spec completion -- allows custom reporters to emit output before the default reporter does. -- Improved focus behavior. Now, this: - - ```golang - FDescribe("Some describe", func() { - It("A", func() {}) - - FIt("B", func() {}) - }) - ``` - - will run `B` but *not* `A`. This tends to be a common usage pattern when in the thick of writing and debugging tests. -- When `SIGINT` is received, Ginkgo will emit the contents of the `GinkgoWriter` before running the `AfterSuite`. Useful for debugging stuck tests. -- When `--progress` is set, Ginkgo will write test progress (in particular, Ginkgo will say when it is about to run a BeforeEach, AfterEach, It, etc...) to the `GinkgoWriter`. This is useful for debugging stuck tests and tests that generate many logs. -- Improved output when an error occurs in a setup or teardown block. -- When `--dryRun` is set, Ginkgo will walk the spec tree and emit to its reporter *without* actually running anything. Best paired with `-v` to understand which specs will run in which order. -- Add `By` to help document long `It`s. `By` simply writes to the `GinkgoWriter`. -- Add support for precompiled tests: - - `ginkgo build ` will now compile the package, producing a file named `package.test` - - The compiled `package.test` file can be run directly. This runs the tests in series. - - To run precompiled tests in parallel, you can run: `ginkgo -p package.test` -- Support `bootstrap`ping and `generate`ing [Agouti](http://agouti.org) specs. -- `ginkgo generate` and `ginkgo bootstrap` now honor the package name already defined in a given directory -- The `ginkgo` CLI ignores `SIGQUIT`. Prevents its stack dump from interlacing with the underlying test suite's stack dump. -- The `ginkgo` CLI now compiles tests into a temporary directory instead of the package directory. This necessitates upgrading to Go v1.4+. -- `ginkgo -notify` now works on Linux - -Bug Fixes: - -- If --skipPackages is used and all packages are skipped, Ginkgo should exit 0. -- Fix tempfile leak when running in parallel -- Fix incorrect failure message when a panic occurs during a parallel test run -- Fixed an issue where a pending test within a focused context (or a focused test within a pending context) would skip all other tests. -- Be more consistent about handling SIGTERM as well as SIGINT -- When interupted while concurrently compiling test suites in the background, Ginkgo now cleans up the compiled artifacts. -- Fixed a long standing bug where `ginkgo -p` would hang if a process spawned by one of the Ginkgo parallel nodes does not exit. (Hooray!) - -## 1.1.0 (8/2/2014) - -No changes, just dropping the beta. - -## 1.1.0-beta (7/22/2014) -New Features: - -- `ginkgo watch` now monitors packages *and their dependencies* for changes. The depth of the dependency tree can be modified with the `-depth` flag. -- Test suites with a programmatic focus (`FIt`, `FDescribe`, etc...) exit with non-zero status code, evne when they pass. This allows CI systems to detect accidental commits of focused test suites. -- `ginkgo -p` runs the testsuite in parallel with an auto-detected number of nodes. -- `ginkgo -tags=TAG_LIST` passes a list of tags down to the `go build` command. -- `ginkgo --failFast` aborts the test suite after the first failure. -- `ginkgo generate file_1 file_2` can take multiple file arguments. -- Ginkgo now summarizes any spec failures that occured at the end of the test run. -- `ginkgo --randomizeSuites` will run tests *suites* in random order using the generated/passed-in seed. - -Improvements: - -- `ginkgo -skipPackage` now takes a comma-separated list of strings. If the *relative path* to a package matches one of the entries in the comma-separated list, that package is skipped. -- `ginkgo --untilItFails` no longer recompiles between attempts. -- Ginkgo now panics when a runnable node (`It`, `BeforeEach`, `JustBeforeEach`, `AfterEach`, `Measure`) is nested within another runnable node. This is always a mistake. Any test suites that panic because of this change should be fixed. - -Bug Fixes: - -- `ginkgo boostrap` and `ginkgo generate` no longer fail when dealing with `hyphen-separated-packages`. -- parallel specs are now better distributed across nodes - fixed a crashing bug where (for example) distributing 11 tests across 7 nodes would panic - -## 1.0.0 (5/24/2014) -New Features: - -- Add `GinkgoParallelNode()` - shorthand for `config.GinkgoConfig.ParallelNode` - -Improvements: - -- When compilation fails, the compilation output is rewritten to present a correct *relative* path. Allows ⌘-clicking in iTerm open the file in your text editor. -- `--untilItFails` and `ginkgo watch` now generate new random seeds between test runs, unless a particular random seed is specified. - -Bug Fixes: - -- `-cover` now generates a correctly combined coverprofile when running with in parallel with multiple `-node`s. -- Print out the contents of the `GinkgoWriter` when `BeforeSuite` or `AfterSuite` fail. -- Fix all remaining race conditions in Ginkgo's test suite. - -## 1.0.0-beta (4/14/2014) -Breaking changes: - -- `thirdparty/gomocktestreporter` is gone. Use `GinkgoT()` instead -- Modified the Reporter interface -- `watch` is now a subcommand, not a flag. - -DSL changes: - -- `BeforeSuite` and `AfterSuite` for setting up and tearing down test suites. -- `AfterSuite` is triggered on interrupt (`^C`) as well as exit. -- `SynchronizedBeforeSuite` and `SynchronizedAfterSuite` for setting up and tearing down singleton resources across parallel nodes. - -CLI changes: - -- `watch` is now a subcommand, not a flag -- `--nodot` flag can be passed to `ginkgo generate` and `ginkgo bootstrap` to avoid dot imports. This explicitly imports all exported identifiers in Ginkgo and Gomega. Refreshing this list can be done by running `ginkgo nodot` -- Additional arguments can be passed to specs. Pass them after the `--` separator -- `--skipPackage` flag takes a regexp and ignores any packages with package names passing said regexp. -- `--trace` flag prints out full stack traces when errors occur, not just the line at which the error occurs. - -Misc: - -- Start using semantic versioning -- Start maintaining changelog - -Major refactor: - -- Pull out Ginkgo's internal to `internal` -- Rename `example` everywhere to `spec` -- Much more! diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/LICENSE b/Godeps/_workspace/src/github.com/onsi/ginkgo/LICENSE deleted file mode 100644 index 9415ee7..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2013-2014 Onsi Fakhouri - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/README.md b/Godeps/_workspace/src/github.com/onsi/ginkgo/README.md deleted file mode 100644 index 2fde2f5..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/README.md +++ /dev/null @@ -1,115 +0,0 @@ -![Ginkgo: A Golang BDD Testing Framework](http://onsi.github.io/ginkgo/images/ginkgo.png) - -[![Build Status](https://travis-ci.org/onsi/ginkgo.png)](https://travis-ci.org/onsi/ginkgo) - -Jump to the [docs](http://onsi.github.io/ginkgo/) to learn more. To start rolling your Ginkgo tests *now* [keep reading](#set-me-up)! - -To discuss Ginkgo and get updates, join the [google group](https://groups.google.com/d/forum/ginkgo-and-gomega). - -## Feature List - -- Ginkgo uses Go's `testing` package and can live alongside your existing `testing` tests. It's easy to [bootstrap](http://onsi.github.io/ginkgo/#bootstrapping-a-suite) and start writing your [first tests](http://onsi.github.io/ginkgo/#adding-specs-to-a-suite) - -- Structure your BDD-style tests expressively: - - Nestable [`Describe` and `Context` container blocks](http://onsi.github.io/ginkgo/#organizing-specs-with-containers-describe-and-context) - - [`BeforeEach` and `AfterEach` blocks](http://onsi.github.io/ginkgo/#extracting-common-setup-beforeeach) for setup and teardown - - [`It` blocks](http://onsi.github.io/ginkgo/#individual-specs-) that hold your assertions - - [`JustBeforeEach` blocks](http://onsi.github.io/ginkgo/#separating-creation-and-configuration-justbeforeeach) that separate creation from configuration (also known as the subject action pattern). - - [`BeforeSuite` and `AfterSuite` blocks](http://onsi.github.io/ginkgo/#global-setup-and-teardown-beforesuite-and-aftersuite) to prep for and cleanup after a suite. - -- A comprehensive test runner that lets you: - - Mark specs as [pending](http://onsi.github.io/ginkgo/#pending-specs) - - [Focus](http://onsi.github.io/ginkgo/#focused-specs) individual specs, and groups of specs, either programmatically or on the command line - - Run your tests in [random order](http://onsi.github.io/ginkgo/#spec-permutation), and then reuse random seeds to replicate the same order. - - Break up your test suite into parallel processes for straightforward [test parallelization](http://onsi.github.io/ginkgo/#parallel-specs) - -- `ginkgo`: a command line interface with plenty of handy command line arguments for [running your tests](http://onsi.github.io/ginkgo/#running-tests) and [generating](http://onsi.github.io/ginkgo/#generators) test files. Here are a few choice examples: - - `ginkgo -nodes=N` runs your tests in `N` parallel processes and print out coherent output in realtime - - `ginkgo -cover` runs your tests using Golang's code coverage tool - - `ginkgo convert` converts an XUnit-style `testing` package to a Ginkgo-style package - - `ginkgo -focus="REGEXP"` and `ginkgo -skip="REGEXP"` allow you to specify a subset of tests to run via regular expression - - `ginkgo -r` runs all tests suites under the current directory - - `ginkgo -v` prints out identifying information for each tests just before it runs - - And much more: run `ginkgo help` for details! - - The `ginkgo` CLI is convenient, but purely optional -- Ginkgo works just fine with `go test` - -- `ginkgo watch` [watches](https://onsi.github.io/ginkgo/#watching-for-changes) packages *and their dependencies* for changes, then reruns tests. Run tests immediately as you develop! - -- Built-in support for testing [asynchronicity](http://onsi.github.io/ginkgo/#asynchronous-tests) - -- Built-in support for [benchmarking](http://onsi.github.io/ginkgo/#benchmark-tests) your code. Control the number of benchmark samples as you gather runtimes and other, arbitrary, bits of numerical information about your code. - -- [Completions for Sublime Text](https://github.com/onsi/ginkgo-sublime-completions): just use [Package Control](https://sublime.wbond.net/) to install `Ginkgo Completions`. - -- Straightforward support for third-party testing libraries such as [Gomock](https://code.google.com/p/gomock/) and [Testify](https://github.com/stretchr/testify). Check out the [docs](http://onsi.github.io/ginkgo/#third-party-integrations) for details. - -- A modular architecture that lets you easily: - - Write [custom reporters](http://onsi.github.io/ginkgo/#writing-custom-reporters) (for example, Ginkgo comes with a [JUnit XML reporter](http://onsi.github.io/ginkgo/#generating-junit-xml-output) and a TeamCity reporter). - - [Adapt an existing matcher library (or write your own!)](http://onsi.github.io/ginkgo/#using-other-matcher-libraries) to work with Ginkgo - -## [Gomega](http://github.com/onsi/gomega): Ginkgo's Preferred Matcher Library - -Ginkgo is best paired with Gomega. Learn more about Gomega [here](http://onsi.github.io/gomega/) - -## [Agouti](http://github.com/sclevine/agouti): A Golang Acceptance Testing Framework - -Agouti allows you run WebDriver integration tests. Learn more about Agouti [here](http://agouti.org) - -## Set Me Up! - -You'll need Golang v1.4+ (Ubuntu users: you probably have Golang v1.0 -- you'll need to upgrade!) - -```bash - -go get github.com/onsi/ginkgo/ginkgo # installs the ginkgo CLI -go get github.com/onsi/gomega # fetches the matcher library - -cd path/to/package/you/want/to/test - -ginkgo bootstrap # set up a new ginkgo suite -ginkgo generate # will create a sample test file. edit this file and add your tests then... - -go test # to run your tests - -ginkgo # also runs your tests - -``` - -## I'm new to Go: What are my testing options? - -Of course, I heartily recommend [Ginkgo](https://github.com/onsi/ginkgo) and [Gomega](https://github.com/onsi/gomega). Both packages are seeing heavy, daily, production use on a number of projects and boast a mature and comprehensive feature-set. - -With that said, it's great to know what your options are :) - -### What Golang gives you out of the box - -Testing is a first class citizen in Golang, however Go's built-in testing primitives are somewhat limited: The [testing](http://golang.org/pkg/testing) package provides basic XUnit style tests and no assertion library. - -### Matcher libraries for Golang's XUnit style tests - -A number of matcher libraries have been written to augment Go's built-in XUnit style tests. Here are two that have gained traction: - -- [testify](https://github.com/stretchr/testify) -- [gocheck](http://labix.org/gocheck) - -You can also use Ginkgo's matcher library [Gomega](https://github.com/onsi/gomega) in [XUnit style tests](http://onsi.github.io/gomega/#using-gomega-with-golangs-xunitstyle-tests) - -### BDD style testing frameworks - -There are a handful of BDD-style testing frameworks written for Golang. Here are a few: - -- [Ginkgo](https://github.com/onsi/ginkgo) ;) -- [GoConvey](https://github.com/smartystreets/goconvey) -- [Goblin](https://github.com/franela/goblin) -- [Mao](https://github.com/azer/mao) -- [Zen](https://github.com/pranavraja/zen) - -Finally, @shageman has [put together](https://github.com/shageman/gotestit) a comprehensive comparison of golang testing libraries. - -Go explore! - -## License - -Ginkgo is MIT-Licensed diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/config/config.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/config/config.go deleted file mode 100644 index 17d911b..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/config/config.go +++ /dev/null @@ -1,170 +0,0 @@ -/* -Ginkgo accepts a number of configuration options. - -These are documented [here](http://onsi.github.io/ginkgo/#the_ginkgo_cli) - -You can also learn more via - - ginkgo help - -or (I kid you not): - - go test -asdf -*/ -package config - -import ( - "flag" - "time" - - "fmt" -) - -const VERSION = "1.2.0-beta" - -type GinkgoConfigType struct { - RandomSeed int64 - RandomizeAllSpecs bool - FocusString string - SkipString string - SkipMeasurements bool - FailOnPending bool - FailFast bool - EmitSpecProgress bool - DryRun bool - - ParallelNode int - ParallelTotal int - SyncHost string - StreamHost string -} - -var GinkgoConfig = GinkgoConfigType{} - -type DefaultReporterConfigType struct { - NoColor bool - SlowSpecThreshold float64 - NoisyPendings bool - Succinct bool - Verbose bool - FullTrace bool -} - -var DefaultReporterConfig = DefaultReporterConfigType{} - -func processPrefix(prefix string) string { - if prefix != "" { - prefix = prefix + "." - } - return prefix -} - -func Flags(flagSet *flag.FlagSet, prefix string, includeParallelFlags bool) { - prefix = processPrefix(prefix) - flagSet.Int64Var(&(GinkgoConfig.RandomSeed), prefix+"seed", time.Now().Unix(), "The seed used to randomize the spec suite.") - flagSet.BoolVar(&(GinkgoConfig.RandomizeAllSpecs), prefix+"randomizeAllSpecs", false, "If set, ginkgo will randomize all specs together. By default, ginkgo only randomizes the top level Describe/Context groups.") - flagSet.BoolVar(&(GinkgoConfig.SkipMeasurements), prefix+"skipMeasurements", false, "If set, ginkgo will skip any measurement specs.") - flagSet.BoolVar(&(GinkgoConfig.FailOnPending), prefix+"failOnPending", false, "If set, ginkgo will mark the test suite as failed if any specs are pending.") - flagSet.BoolVar(&(GinkgoConfig.FailFast), prefix+"failFast", false, "If set, ginkgo will stop running a test suite after a failure occurs.") - flagSet.BoolVar(&(GinkgoConfig.DryRun), prefix+"dryRun", false, "If set, ginkgo will walk the test hierarchy without actually running anything. Best paired with -v.") - flagSet.StringVar(&(GinkgoConfig.FocusString), prefix+"focus", "", "If set, ginkgo will only run specs that match this regular expression.") - flagSet.StringVar(&(GinkgoConfig.SkipString), prefix+"skip", "", "If set, ginkgo will only run specs that do not match this regular expression.") - flagSet.BoolVar(&(GinkgoConfig.EmitSpecProgress), prefix+"progress", false, "If set, ginkgo will emit progress information as each spec runs to the GinkgoWriter.") - - if includeParallelFlags { - flagSet.IntVar(&(GinkgoConfig.ParallelNode), prefix+"parallel.node", 1, "This worker node's (one-indexed) node number. For running specs in parallel.") - flagSet.IntVar(&(GinkgoConfig.ParallelTotal), prefix+"parallel.total", 1, "The total number of worker nodes. For running specs in parallel.") - flagSet.StringVar(&(GinkgoConfig.SyncHost), prefix+"parallel.synchost", "", "The address for the server that will synchronize the running nodes.") - flagSet.StringVar(&(GinkgoConfig.StreamHost), prefix+"parallel.streamhost", "", "The address for the server that the running nodes should stream data to.") - } - - flagSet.BoolVar(&(DefaultReporterConfig.NoColor), prefix+"noColor", false, "If set, suppress color output in default reporter.") - flagSet.Float64Var(&(DefaultReporterConfig.SlowSpecThreshold), prefix+"slowSpecThreshold", 5.0, "(in seconds) Specs that take longer to run than this threshold are flagged as slow by the default reporter (default: 5 seconds).") - flagSet.BoolVar(&(DefaultReporterConfig.NoisyPendings), prefix+"noisyPendings", true, "If set, default reporter will shout about pending tests.") - flagSet.BoolVar(&(DefaultReporterConfig.Verbose), prefix+"v", false, "If set, default reporter print out all specs as they begin.") - flagSet.BoolVar(&(DefaultReporterConfig.Succinct), prefix+"succinct", false, "If set, default reporter prints out a very succinct report") - flagSet.BoolVar(&(DefaultReporterConfig.FullTrace), prefix+"trace", false, "If set, default reporter prints out the full stack trace when a failure occurs") -} - -func BuildFlagArgs(prefix string, ginkgo GinkgoConfigType, reporter DefaultReporterConfigType) []string { - prefix = processPrefix(prefix) - result := make([]string, 0) - - if ginkgo.RandomSeed > 0 { - result = append(result, fmt.Sprintf("--%sseed=%d", prefix, ginkgo.RandomSeed)) - } - - if ginkgo.RandomizeAllSpecs { - result = append(result, fmt.Sprintf("--%srandomizeAllSpecs", prefix)) - } - - if ginkgo.SkipMeasurements { - result = append(result, fmt.Sprintf("--%sskipMeasurements", prefix)) - } - - if ginkgo.FailOnPending { - result = append(result, fmt.Sprintf("--%sfailOnPending", prefix)) - } - - if ginkgo.FailFast { - result = append(result, fmt.Sprintf("--%sfailFast", prefix)) - } - - if ginkgo.DryRun { - result = append(result, fmt.Sprintf("--%sdryRun", prefix)) - } - - if ginkgo.FocusString != "" { - result = append(result, fmt.Sprintf("--%sfocus=%s", prefix, ginkgo.FocusString)) - } - - if ginkgo.SkipString != "" { - result = append(result, fmt.Sprintf("--%sskip=%s", prefix, ginkgo.SkipString)) - } - - if ginkgo.EmitSpecProgress { - result = append(result, fmt.Sprintf("--%sprogress", prefix)) - } - - if ginkgo.ParallelNode != 0 { - result = append(result, fmt.Sprintf("--%sparallel.node=%d", prefix, ginkgo.ParallelNode)) - } - - if ginkgo.ParallelTotal != 0 { - result = append(result, fmt.Sprintf("--%sparallel.total=%d", prefix, ginkgo.ParallelTotal)) - } - - if ginkgo.StreamHost != "" { - result = append(result, fmt.Sprintf("--%sparallel.streamhost=%s", prefix, ginkgo.StreamHost)) - } - - if ginkgo.SyncHost != "" { - result = append(result, fmt.Sprintf("--%sparallel.synchost=%s", prefix, ginkgo.SyncHost)) - } - - if reporter.NoColor { - result = append(result, fmt.Sprintf("--%snoColor", prefix)) - } - - if reporter.SlowSpecThreshold > 0 { - result = append(result, fmt.Sprintf("--%sslowSpecThreshold=%.5f", prefix, reporter.SlowSpecThreshold)) - } - - if !reporter.NoisyPendings { - result = append(result, fmt.Sprintf("--%snoisyPendings=false", prefix)) - } - - if reporter.Verbose { - result = append(result, fmt.Sprintf("--%sv", prefix)) - } - - if reporter.Succinct { - result = append(result, fmt.Sprintf("--%ssuccinct", prefix)) - } - - if reporter.FullTrace { - result = append(result, fmt.Sprintf("--%strace", prefix)) - } - - return result -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/bootstrap_command.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/bootstrap_command.go deleted file mode 100644 index d804fe0..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/bootstrap_command.go +++ /dev/null @@ -1,182 +0,0 @@ -package main - -import ( - "bytes" - "flag" - "fmt" - "os" - "path/filepath" - "strings" - "text/template" - - "go/build" - - "github.com/onsi/ginkgo/ginkgo/nodot" -) - -func BuildBootstrapCommand() *Command { - var agouti, noDot bool - flagSet := flag.NewFlagSet("bootstrap", flag.ExitOnError) - flagSet.BoolVar(&agouti, "agouti", false, "If set, bootstrap will generate a bootstrap file for writing Agouti tests") - flagSet.BoolVar(&noDot, "nodot", false, "If set, bootstrap will generate a bootstrap file that does not . import ginkgo and gomega") - - return &Command{ - Name: "bootstrap", - FlagSet: flagSet, - UsageCommand: "ginkgo bootstrap ", - Usage: []string{ - "Bootstrap a test suite for the current package", - "Accepts the following flags:", - }, - Command: func(args []string, additionalArgs []string) { - generateBootstrap(agouti, noDot) - }, - } -} - -var bootstrapText = `package {{.Package}}_test - -import ( - {{.GinkgoImport}} - {{.GomegaImport}} - - "testing" -) - -func Test{{.FormattedName}}(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "{{.FormattedName}} Suite") -} -` - -var agoutiBootstrapText = `package {{.Package}}_test - -import ( - {{.GinkgoImport}} - {{.GomegaImport}} - "github.com/sclevine/agouti" - - "testing" -) - -func Test{{.FormattedName}}(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "{{.FormattedName}} Suite") -} - -var agoutiDriver *agouti.WebDriver - -var _ = BeforeSuite(func() { - // Choose a WebDriver: - - agoutiDriver = agouti.PhantomJS() - // agoutiDriver = agouti.Selenium() - // agoutiDriver = agouti.ChromeDriver() - - Expect(agoutiDriver.Start()).To(Succeed()) -}) - -var _ = AfterSuite(func() { - Expect(agoutiDriver.Stop()).To(Succeed()) -}) -` - -type bootstrapData struct { - Package string - FormattedName string - GinkgoImport string - GomegaImport string -} - -func getPackageAndFormattedName() (string, string, string) { - path, err := os.Getwd() - if err != nil { - complainAndQuit("Could not get current working directory: \n" + err.Error()) - } - - dirName := strings.Replace(filepath.Base(path), "-", "_", -1) - dirName = strings.Replace(dirName, " ", "_", -1) - - pkg, err := build.ImportDir(path, 0) - packageName := pkg.Name - if err != nil { - packageName = dirName - } - - formattedName := prettifyPackageName(filepath.Base(path)) - return packageName, dirName, formattedName -} - -func prettifyPackageName(name string) string { - name = strings.Replace(name, "-", " ", -1) - name = strings.Replace(name, "_", " ", -1) - name = strings.Title(name) - name = strings.Replace(name, " ", "", -1) - return name -} - -func fileExists(path string) bool { - _, err := os.Stat(path) - if err == nil { - return true - } - return false -} - -func generateBootstrap(agouti bool, noDot bool) { - packageName, bootstrapFilePrefix, formattedName := getPackageAndFormattedName() - data := bootstrapData{ - Package: packageName, - FormattedName: formattedName, - GinkgoImport: `. "github.com/onsi/ginkgo"`, - GomegaImport: `. "github.com/onsi/gomega"`, - } - - if noDot { - data.GinkgoImport = `"github.com/onsi/ginkgo"` - data.GomegaImport = `"github.com/onsi/gomega"` - } - - targetFile := fmt.Sprintf("%s_suite_test.go", bootstrapFilePrefix) - if fileExists(targetFile) { - fmt.Printf("%s already exists.\n\n", targetFile) - os.Exit(1) - } else { - fmt.Printf("Generating ginkgo test suite bootstrap for %s in:\n\t%s\n", packageName, targetFile) - } - - f, err := os.Create(targetFile) - if err != nil { - complainAndQuit("Could not create file: " + err.Error()) - panic(err.Error()) - } - defer f.Close() - - var templateText string - if agouti { - templateText = agoutiBootstrapText - } else { - templateText = bootstrapText - } - - bootstrapTemplate, err := template.New("bootstrap").Parse(templateText) - if err != nil { - panic(err.Error()) - } - - buf := &bytes.Buffer{} - bootstrapTemplate.Execute(buf, data) - - if noDot { - contents, err := nodot.ApplyNoDot(buf.Bytes()) - if err != nil { - complainAndQuit("Failed to import nodot declarations: " + err.Error()) - } - fmt.Println("To update the nodot declarations in the future, switch to this directory and run:\n\tginkgo nodot") - buf = bytes.NewBuffer(contents) - } - - buf.WriteTo(f) - - goFmt(targetFile) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/build_command.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/build_command.go deleted file mode 100644 index bbba8a1..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/build_command.go +++ /dev/null @@ -1,68 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "os" - "path/filepath" - - "github.com/onsi/ginkgo/ginkgo/interrupthandler" - "github.com/onsi/ginkgo/ginkgo/testrunner" -) - -func BuildBuildCommand() *Command { - commandFlags := NewBuildCommandFlags(flag.NewFlagSet("build", flag.ExitOnError)) - interruptHandler := interrupthandler.NewInterruptHandler() - builder := &SpecBuilder{ - commandFlags: commandFlags, - interruptHandler: interruptHandler, - } - - return &Command{ - Name: "build", - FlagSet: commandFlags.FlagSet, - UsageCommand: "ginkgo build ", - Usage: []string{ - "Build the passed in (or the package in the current directory if left blank).", - "Accepts the following flags:", - }, - Command: builder.BuildSpecs, - } -} - -type SpecBuilder struct { - commandFlags *RunWatchAndBuildCommandFlags - interruptHandler *interrupthandler.InterruptHandler -} - -func (r *SpecBuilder) BuildSpecs(args []string, additionalArgs []string) { - r.commandFlags.computeNodes() - - suites, _ := findSuites(args, r.commandFlags.Recurse, r.commandFlags.SkipPackage, false) - - if len(suites) == 0 { - complainAndQuit("Found no test suites") - } - - passed := true - for _, suite := range suites { - runner := testrunner.New(suite, 1, false, r.commandFlags.Race, r.commandFlags.Cover, r.commandFlags.CoverPkg, r.commandFlags.Tags, nil) - fmt.Printf("Compiling %s...\n", suite.PackageName) - - path, _ := filepath.Abs(filepath.Join(suite.Path, fmt.Sprintf("%s.test", suite.PackageName))) - err := runner.CompileTo(path) - if err != nil { - fmt.Println(err.Error()) - passed = false - } else { - fmt.Printf(" compiled %s.test\n", suite.PackageName) - } - - runner.CleanUp() - } - - if passed { - os.Exit(0) - } - os.Exit(1) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/ginkgo_ast_nodes.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/ginkgo_ast_nodes.go deleted file mode 100644 index 02e2b3b..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/ginkgo_ast_nodes.go +++ /dev/null @@ -1,123 +0,0 @@ -package convert - -import ( - "fmt" - "go/ast" - "strings" - "unicode" -) - -/* - * Creates a func init() node - */ -func createVarUnderscoreBlock() *ast.ValueSpec { - valueSpec := &ast.ValueSpec{} - object := &ast.Object{Kind: 4, Name: "_", Decl: valueSpec, Data: 0} - ident := &ast.Ident{Name: "_", Obj: object} - valueSpec.Names = append(valueSpec.Names, ident) - return valueSpec -} - -/* - * Creates a Describe("Testing with ginkgo", func() { }) node - */ -func createDescribeBlock() *ast.CallExpr { - blockStatement := &ast.BlockStmt{List: []ast.Stmt{}} - - fieldList := &ast.FieldList{} - funcType := &ast.FuncType{Params: fieldList} - funcLit := &ast.FuncLit{Type: funcType, Body: blockStatement} - basicLit := &ast.BasicLit{Kind: 9, Value: "\"Testing with Ginkgo\""} - describeIdent := &ast.Ident{Name: "Describe"} - return &ast.CallExpr{Fun: describeIdent, Args: []ast.Expr{basicLit, funcLit}} -} - -/* - * Convenience function to return the name of the *testing.T param - * for a Test function that will be rewritten. This is useful because - * we will want to replace the usage of this named *testing.T inside the - * body of the function with a GinktoT. - */ -func namedTestingTArg(node *ast.FuncDecl) string { - return node.Type.Params.List[0].Names[0].Name // *exhale* -} - -/* - * Convenience function to return the block statement node for a Describe statement - */ -func blockStatementFromDescribe(desc *ast.CallExpr) *ast.BlockStmt { - var funcLit *ast.FuncLit - var found = false - - for _, node := range desc.Args { - switch node := node.(type) { - case *ast.FuncLit: - found = true - funcLit = node - break - } - } - - if !found { - panic("Error finding ast.FuncLit inside describe statement. Somebody done goofed.") - } - - return funcLit.Body -} - -/* convenience function for creating an It("TestNameHere") - * with all the body of the test function inside the anonymous - * func passed to It() - */ -func createItStatementForTestFunc(testFunc *ast.FuncDecl) *ast.ExprStmt { - blockStatement := &ast.BlockStmt{List: testFunc.Body.List} - fieldList := &ast.FieldList{} - funcType := &ast.FuncType{Params: fieldList} - funcLit := &ast.FuncLit{Type: funcType, Body: blockStatement} - - testName := rewriteTestName(testFunc.Name.Name) - basicLit := &ast.BasicLit{Kind: 9, Value: fmt.Sprintf("\"%s\"", testName)} - itBlockIdent := &ast.Ident{Name: "It"} - callExpr := &ast.CallExpr{Fun: itBlockIdent, Args: []ast.Expr{basicLit, funcLit}} - return &ast.ExprStmt{X: callExpr} -} - -/* -* rewrite test names to be human readable -* eg: rewrites "TestSomethingAmazing" as "something amazing" - */ -func rewriteTestName(testName string) string { - nameComponents := []string{} - currentString := "" - indexOfTest := strings.Index(testName, "Test") - if indexOfTest != 0 { - return testName - } - - testName = strings.Replace(testName, "Test", "", 1) - first, rest := testName[0], testName[1:] - testName = string(unicode.ToLower(rune(first))) + rest - - for _, rune := range testName { - if unicode.IsUpper(rune) { - nameComponents = append(nameComponents, currentString) - currentString = string(unicode.ToLower(rune)) - } else { - currentString += string(rune) - } - } - - return strings.Join(append(nameComponents, currentString), " ") -} - -func newGinkgoTFromIdent(ident *ast.Ident) *ast.CallExpr { - return &ast.CallExpr{ - Lparen: ident.NamePos + 1, - Rparen: ident.NamePos + 2, - Fun: &ast.Ident{Name: "GinkgoT"}, - } -} - -func newGinkgoTInterface() *ast.Ident { - return &ast.Ident{Name: "GinkgoTInterface"} -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/import.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/import.go deleted file mode 100644 index e226196..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/import.go +++ /dev/null @@ -1,91 +0,0 @@ -package convert - -import ( - "errors" - "fmt" - "go/ast" -) - -/* - * Given the root node of an AST, returns the node containing the - * import statements for the file. - */ -func importsForRootNode(rootNode *ast.File) (imports *ast.GenDecl, err error) { - for _, declaration := range rootNode.Decls { - decl, ok := declaration.(*ast.GenDecl) - if !ok || len(decl.Specs) == 0 { - continue - } - - _, ok = decl.Specs[0].(*ast.ImportSpec) - if ok { - imports = decl - return - } - } - - err = errors.New(fmt.Sprintf("Could not find imports for root node:\n\t%#v\n", rootNode)) - return -} - -/* - * Removes "testing" import, if present - */ -func removeTestingImport(rootNode *ast.File) { - importDecl, err := importsForRootNode(rootNode) - if err != nil { - panic(err.Error()) - } - - var index int - for i, importSpec := range importDecl.Specs { - importSpec := importSpec.(*ast.ImportSpec) - if importSpec.Path.Value == "\"testing\"" { - index = i - break - } - } - - importDecl.Specs = append(importDecl.Specs[:index], importDecl.Specs[index+1:]...) -} - -/* - * Adds import statements for onsi/ginkgo, if missing - */ -func addGinkgoImports(rootNode *ast.File) { - importDecl, err := importsForRootNode(rootNode) - if err != nil { - panic(err.Error()) - } - - if len(importDecl.Specs) == 0 { - // TODO: might need to create a import decl here - panic("unimplemented : expected to find an imports block") - } - - needsGinkgo := true - for _, importSpec := range importDecl.Specs { - importSpec, ok := importSpec.(*ast.ImportSpec) - if !ok { - continue - } - - if importSpec.Path.Value == "\"github.com/onsi/ginkgo\"" { - needsGinkgo = false - } - } - - if needsGinkgo { - importDecl.Specs = append(importDecl.Specs, createImport(".", "\"github.com/onsi/ginkgo\"")) - } -} - -/* - * convenience function to create an import statement - */ -func createImport(name, path string) *ast.ImportSpec { - return &ast.ImportSpec{ - Name: &ast.Ident{Name: name}, - Path: &ast.BasicLit{Kind: 9, Value: path}, - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/package_rewriter.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/package_rewriter.go deleted file mode 100644 index ed09c46..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/package_rewriter.go +++ /dev/null @@ -1,127 +0,0 @@ -package convert - -import ( - "fmt" - "go/build" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "regexp" -) - -/* - * RewritePackage takes a name (eg: my-package/tools), finds its test files using - * Go's build package, and then rewrites them. A ginkgo test suite file will - * also be added for this package, and all of its child packages. - */ -func RewritePackage(packageName string) { - pkg, err := packageWithName(packageName) - if err != nil { - panic(fmt.Sprintf("unexpected error reading package: '%s'\n%s\n", packageName, err.Error())) - } - - for _, filename := range findTestsInPackage(pkg) { - rewriteTestsInFile(filename) - } - return -} - -/* - * Given a package, findTestsInPackage reads the test files in the directory, - * and then recurses on each child package, returning a slice of all test files - * found in this process. - */ -func findTestsInPackage(pkg *build.Package) (testfiles []string) { - for _, file := range append(pkg.TestGoFiles, pkg.XTestGoFiles...) { - testfiles = append(testfiles, filepath.Join(pkg.Dir, file)) - } - - dirFiles, err := ioutil.ReadDir(pkg.Dir) - if err != nil { - panic(fmt.Sprintf("unexpected error reading dir: '%s'\n%s\n", pkg.Dir, err.Error())) - } - - re := regexp.MustCompile(`^[._]`) - - for _, file := range dirFiles { - if !file.IsDir() { - continue - } - - if re.Match([]byte(file.Name())) { - continue - } - - packageName := filepath.Join(pkg.ImportPath, file.Name()) - subPackage, err := packageWithName(packageName) - if err != nil { - panic(fmt.Sprintf("unexpected error reading package: '%s'\n%s\n", packageName, err.Error())) - } - - testfiles = append(testfiles, findTestsInPackage(subPackage)...) - } - - addGinkgoSuiteForPackage(pkg) - goFmtPackage(pkg) - return -} - -/* - * Shells out to `ginkgo bootstrap` to create a test suite file - */ -func addGinkgoSuiteForPackage(pkg *build.Package) { - originalDir, err := os.Getwd() - if err != nil { - panic(err) - } - - suite_test_file := filepath.Join(pkg.Dir, pkg.Name+"_suite_test.go") - - _, err = os.Stat(suite_test_file) - if err == nil { - return // test file already exists, this should be a no-op - } - - err = os.Chdir(pkg.Dir) - if err != nil { - panic(err) - } - - output, err := exec.Command("ginkgo", "bootstrap").Output() - - if err != nil { - panic(fmt.Sprintf("error running 'ginkgo bootstrap'.\nstdout: %s\n%s\n", output, err.Error())) - } - - err = os.Chdir(originalDir) - if err != nil { - panic(err) - } -} - -/* - * Shells out to `go fmt` to format the package - */ -func goFmtPackage(pkg *build.Package) { - output, err := exec.Command("go", "fmt", pkg.ImportPath).Output() - - if err != nil { - fmt.Printf("Warning: Error running 'go fmt %s'.\nstdout: %s\n%s\n", pkg.ImportPath, output, err.Error()) - } -} - -/* - * Attempts to return a package with its test files already read. - * The ImportMode arg to build.Import lets you specify if you want go to read the - * buildable go files inside the package, but it fails if the package has no go files - */ -func packageWithName(name string) (pkg *build.Package, err error) { - pkg, err = build.Default.Import(name, ".", build.ImportMode(0)) - if err == nil { - return - } - - pkg, err = build.Default.Import(name, ".", build.ImportMode(1)) - return -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/test_finder.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/test_finder.go deleted file mode 100644 index b33595c..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/test_finder.go +++ /dev/null @@ -1,56 +0,0 @@ -package convert - -import ( - "go/ast" - "regexp" -) - -/* - * Given a root node, walks its top level statements and returns - * points to function nodes to rewrite as It statements. - * These functions, according to Go testing convention, must be named - * TestWithCamelCasedName and receive a single *testing.T argument. - */ -func findTestFuncs(rootNode *ast.File) (testsToRewrite []*ast.FuncDecl) { - testNameRegexp := regexp.MustCompile("^Test[0-9A-Z].+") - - ast.Inspect(rootNode, func(node ast.Node) bool { - if node == nil { - return false - } - - switch node := node.(type) { - case *ast.FuncDecl: - matches := testNameRegexp.MatchString(node.Name.Name) - - if matches && receivesTestingT(node) { - testsToRewrite = append(testsToRewrite, node) - } - } - - return true - }) - - return -} - -/* - * convenience function that looks at args to a function and determines if its - * params include an argument of type *testing.T - */ -func receivesTestingT(node *ast.FuncDecl) bool { - if len(node.Type.Params.List) != 1 { - return false - } - - base, ok := node.Type.Params.List[0].Type.(*ast.StarExpr) - if !ok { - return false - } - - intermediate := base.X.(*ast.SelectorExpr) - isTestingPackage := intermediate.X.(*ast.Ident).Name == "testing" - isTestingT := intermediate.Sel.Name == "T" - - return isTestingPackage && isTestingT -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/testfile_rewriter.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/testfile_rewriter.go deleted file mode 100644 index 4b001a7..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/testfile_rewriter.go +++ /dev/null @@ -1,163 +0,0 @@ -package convert - -import ( - "bytes" - "fmt" - "go/ast" - "go/format" - "go/parser" - "go/token" - "io/ioutil" - "os" -) - -/* - * Given a file path, rewrites any tests in the Ginkgo format. - * First, we parse the AST, and update the imports declaration. - * Then, we walk the first child elements in the file, returning tests to rewrite. - * A top level init func is declared, with a single Describe func inside. - * Then the test functions to rewrite are inserted as It statements inside the Describe. - * Finally we walk the rest of the file, replacing other usages of *testing.T - * Once that is complete, we write the AST back out again to its file. - */ -func rewriteTestsInFile(pathToFile string) { - fileSet := token.NewFileSet() - rootNode, err := parser.ParseFile(fileSet, pathToFile, nil, 0) - if err != nil { - panic(fmt.Sprintf("Error parsing test file '%s':\n%s\n", pathToFile, err.Error())) - } - - addGinkgoImports(rootNode) - removeTestingImport(rootNode) - - varUnderscoreBlock := createVarUnderscoreBlock() - describeBlock := createDescribeBlock() - varUnderscoreBlock.Values = []ast.Expr{describeBlock} - - for _, testFunc := range findTestFuncs(rootNode) { - rewriteTestFuncAsItStatement(testFunc, rootNode, describeBlock) - } - - underscoreDecl := &ast.GenDecl{ - Tok: 85, // gah, magick numbers are needed to make this work - TokPos: 14, // this tricks Go into writing "var _ = Describe" - Specs: []ast.Spec{varUnderscoreBlock}, - } - - imports := rootNode.Decls[0] - tail := rootNode.Decls[1:] - rootNode.Decls = append(append([]ast.Decl{imports}, underscoreDecl), tail...) - rewriteOtherFuncsToUseGinkgoT(rootNode.Decls) - walkNodesInRootNodeReplacingTestingT(rootNode) - - var buffer bytes.Buffer - if err = format.Node(&buffer, fileSet, rootNode); err != nil { - panic(fmt.Sprintf("Error formatting ast node after rewriting tests.\n%s\n", err.Error())) - } - - fileInfo, err := os.Stat(pathToFile) - if err != nil { - panic(fmt.Sprintf("Error stat'ing file: %s\n", pathToFile)) - } - - ioutil.WriteFile(pathToFile, buffer.Bytes(), fileInfo.Mode()) - return -} - -/* - * Given a test func named TestDoesSomethingNeat, rewrites it as - * It("does something neat", func() { __test_body_here__ }) and adds it - * to the Describe's list of statements - */ -func rewriteTestFuncAsItStatement(testFunc *ast.FuncDecl, rootNode *ast.File, describe *ast.CallExpr) { - var funcIndex int = -1 - for index, child := range rootNode.Decls { - if child == testFunc { - funcIndex = index - break - } - } - - if funcIndex < 0 { - panic(fmt.Sprintf("Assert failed: Error finding index for test node %s\n", testFunc.Name.Name)) - } - - var block *ast.BlockStmt = blockStatementFromDescribe(describe) - block.List = append(block.List, createItStatementForTestFunc(testFunc)) - replaceTestingTsWithGinkgoT(block, namedTestingTArg(testFunc)) - - // remove the old test func from the root node's declarations - rootNode.Decls = append(rootNode.Decls[:funcIndex], rootNode.Decls[funcIndex+1:]...) - return -} - -/* - * walks nodes inside of a test func's statements and replaces the usage of - * it's named *testing.T param with GinkgoT's - */ -func replaceTestingTsWithGinkgoT(statementsBlock *ast.BlockStmt, testingT string) { - ast.Inspect(statementsBlock, func(node ast.Node) bool { - if node == nil { - return false - } - - keyValueExpr, ok := node.(*ast.KeyValueExpr) - if ok { - replaceNamedTestingTsInKeyValueExpression(keyValueExpr, testingT) - return true - } - - funcLiteral, ok := node.(*ast.FuncLit) - if ok { - replaceTypeDeclTestingTsInFuncLiteral(funcLiteral) - return true - } - - callExpr, ok := node.(*ast.CallExpr) - if !ok { - return true - } - replaceTestingTsInArgsLists(callExpr, testingT) - - funCall, ok := callExpr.Fun.(*ast.SelectorExpr) - if ok { - replaceTestingTsMethodCalls(funCall, testingT) - } - - return true - }) -} - -/* - * rewrite t.Fail() or any other *testing.T method by replacing with T().Fail() - * This function receives a selector expression (eg: t.Fail()) and - * the name of the *testing.T param from the function declaration. Rewrites the - * selector expression in place if the target was a *testing.T - */ -func replaceTestingTsMethodCalls(selectorExpr *ast.SelectorExpr, testingT string) { - ident, ok := selectorExpr.X.(*ast.Ident) - if !ok { - return - } - - if ident.Name == testingT { - selectorExpr.X = newGinkgoTFromIdent(ident) - } -} - -/* - * replaces usages of a named *testing.T param inside of a call expression - * with a new GinkgoT object - */ -func replaceTestingTsInArgsLists(callExpr *ast.CallExpr, testingT string) { - for index, arg := range callExpr.Args { - ident, ok := arg.(*ast.Ident) - if !ok { - continue - } - - if ident.Name == testingT { - callExpr.Args[index] = newGinkgoTFromIdent(ident) - } - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/testing_t_rewriter.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/testing_t_rewriter.go deleted file mode 100644 index 418cdc4..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert/testing_t_rewriter.go +++ /dev/null @@ -1,130 +0,0 @@ -package convert - -import ( - "go/ast" -) - -/* - * Rewrites any other top level funcs that receive a *testing.T param - */ -func rewriteOtherFuncsToUseGinkgoT(declarations []ast.Decl) { - for _, decl := range declarations { - decl, ok := decl.(*ast.FuncDecl) - if !ok { - continue - } - - for _, param := range decl.Type.Params.List { - starExpr, ok := param.Type.(*ast.StarExpr) - if !ok { - continue - } - - selectorExpr, ok := starExpr.X.(*ast.SelectorExpr) - if !ok { - continue - } - - xIdent, ok := selectorExpr.X.(*ast.Ident) - if !ok || xIdent.Name != "testing" { - continue - } - - if selectorExpr.Sel.Name != "T" { - continue - } - - param.Type = newGinkgoTInterface() - } - } -} - -/* - * Walks all of the nodes in the file, replacing *testing.T in struct - * and func literal nodes. eg: - * type foo struct { *testing.T } - * var bar = func(t *testing.T) { } - */ -func walkNodesInRootNodeReplacingTestingT(rootNode *ast.File) { - ast.Inspect(rootNode, func(node ast.Node) bool { - if node == nil { - return false - } - - switch node := node.(type) { - case *ast.StructType: - replaceTestingTsInStructType(node) - case *ast.FuncLit: - replaceTypeDeclTestingTsInFuncLiteral(node) - } - - return true - }) -} - -/* - * replaces named *testing.T inside a composite literal - */ -func replaceNamedTestingTsInKeyValueExpression(kve *ast.KeyValueExpr, testingT string) { - ident, ok := kve.Value.(*ast.Ident) - if !ok { - return - } - - if ident.Name == testingT { - kve.Value = newGinkgoTFromIdent(ident) - } -} - -/* - * replaces *testing.T params in a func literal with GinkgoT - */ -func replaceTypeDeclTestingTsInFuncLiteral(functionLiteral *ast.FuncLit) { - for _, arg := range functionLiteral.Type.Params.List { - starExpr, ok := arg.Type.(*ast.StarExpr) - if !ok { - continue - } - - selectorExpr, ok := starExpr.X.(*ast.SelectorExpr) - if !ok { - continue - } - - target, ok := selectorExpr.X.(*ast.Ident) - if !ok { - continue - } - - if target.Name == "testing" && selectorExpr.Sel.Name == "T" { - arg.Type = newGinkgoTInterface() - } - } -} - -/* - * Replaces *testing.T types inside of a struct declaration with a GinkgoT - * eg: type foo struct { *testing.T } - */ -func replaceTestingTsInStructType(structType *ast.StructType) { - for _, field := range structType.Fields.List { - starExpr, ok := field.Type.(*ast.StarExpr) - if !ok { - continue - } - - selectorExpr, ok := starExpr.X.(*ast.SelectorExpr) - if !ok { - continue - } - - xIdent, ok := selectorExpr.X.(*ast.Ident) - if !ok { - continue - } - - if xIdent.Name == "testing" && selectorExpr.Sel.Name == "T" { - field.Type = newGinkgoTInterface() - } - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert_command.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert_command.go deleted file mode 100644 index 89e60d3..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/convert_command.go +++ /dev/null @@ -1,44 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "github.com/onsi/ginkgo/ginkgo/convert" - "os" -) - -func BuildConvertCommand() *Command { - return &Command{ - Name: "convert", - FlagSet: flag.NewFlagSet("convert", flag.ExitOnError), - UsageCommand: "ginkgo convert /path/to/package", - Usage: []string{ - "Convert the package at the passed in path from an XUnit-style test to a Ginkgo-style test", - }, - Command: convertPackage, - } -} - -func convertPackage(args []string, additionalArgs []string) { - if len(args) != 1 { - println(fmt.Sprintf("usage: ginkgo convert /path/to/your/package")) - os.Exit(1) - } - - defer func() { - err := recover() - if err != nil { - switch err := err.(type) { - case error: - println(err.Error()) - case string: - println(err) - default: - println(fmt.Sprintf("unexpected error: %#v", err)) - } - os.Exit(1) - } - }() - - convert.RewritePackage(args[0]) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/generate_command.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/generate_command.go deleted file mode 100644 index 7dd3b4d..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/generate_command.go +++ /dev/null @@ -1,164 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "os" - "path/filepath" - "strings" - "text/template" -) - -func BuildGenerateCommand() *Command { - var agouti, noDot bool - flagSet := flag.NewFlagSet("generate", flag.ExitOnError) - flagSet.BoolVar(&agouti, "agouti", false, "If set, generate will generate a test file for writing Agouti tests") - flagSet.BoolVar(&noDot, "nodot", false, "If set, generate will generate a test file that does not . import ginkgo and gomega") - - return &Command{ - Name: "generate", - FlagSet: flagSet, - UsageCommand: "ginkgo generate ", - Usage: []string{ - "Generate a test file named filename_test.go", - "If the optional argument is omitted, a file named after the package in the current directory will be created.", - "Accepts the following flags:", - }, - Command: func(args []string, additionalArgs []string) { - generateSpec(args, agouti, noDot) - }, - } -} - -var specText = `package {{.Package}}_test - -import ( - . "{{.PackageImportPath}}" - - {{if .IncludeImports}}. "github.com/onsi/ginkgo"{{end}} - {{if .IncludeImports}}. "github.com/onsi/gomega"{{end}} -) - -var _ = Describe("{{.Subject}}", func() { - -}) -` - -var agoutiSpecText = `package {{.Package}}_test - -import ( - . "{{.PackageImportPath}}" - - {{if .IncludeImports}}. "github.com/onsi/ginkgo"{{end}} - {{if .IncludeImports}}. "github.com/onsi/gomega"{{end}} - . "github.com/sclevine/agouti/matchers" - "github.com/sclevine/agouti" -) - -var _ = Describe("{{.Subject}}", func() { - var page *agouti.Page - - BeforeEach(func() { - var err error - page, err = agoutiDriver.NewPage() - Expect(err).NotTo(HaveOccurred()) - }) - - AfterEach(func() { - Expect(page.Destroy()).To(Succeed()) - }) -}) -` - -type specData struct { - Package string - Subject string - PackageImportPath string - IncludeImports bool -} - -func generateSpec(args []string, agouti, noDot bool) { - if len(args) == 0 { - err := generateSpecForSubject("", agouti, noDot) - if err != nil { - fmt.Println(err.Error()) - fmt.Println("") - os.Exit(1) - } - fmt.Println("") - return - } - - var failed bool - for _, arg := range args { - err := generateSpecForSubject(arg, agouti, noDot) - if err != nil { - failed = true - fmt.Println(err.Error()) - } - } - fmt.Println("") - if failed { - os.Exit(1) - } -} - -func generateSpecForSubject(subject string, agouti, noDot bool) error { - packageName, specFilePrefix, formattedName := getPackageAndFormattedName() - if subject != "" { - subject = strings.Split(subject, ".go")[0] - subject = strings.Split(subject, "_test")[0] - specFilePrefix = subject - formattedName = prettifyPackageName(subject) - } - - data := specData{ - Package: packageName, - Subject: formattedName, - PackageImportPath: getPackageImportPath(), - IncludeImports: !noDot, - } - - targetFile := fmt.Sprintf("%s_test.go", specFilePrefix) - if fileExists(targetFile) { - return fmt.Errorf("%s already exists.", targetFile) - } else { - fmt.Printf("Generating ginkgo test for %s in:\n %s\n", data.Subject, targetFile) - } - - f, err := os.Create(targetFile) - if err != nil { - return err - } - defer f.Close() - - var templateText string - if agouti { - templateText = agoutiSpecText - } else { - templateText = specText - } - - specTemplate, err := template.New("spec").Parse(templateText) - if err != nil { - return err - } - - specTemplate.Execute(f, data) - goFmt(targetFile) - return nil -} - -func getPackageImportPath() string { - workingDir, err := os.Getwd() - if err != nil { - panic(err.Error()) - } - sep := string(filepath.Separator) - paths := strings.Split(workingDir, sep+"src"+sep) - if len(paths) == 1 { - fmt.Printf("\nCouldn't identify package import path.\n\n\tginkgo generate\n\nMust be run within a package directory under $GOPATH/src/...\nYou're going to have to change UNKNOWN_PACKAGE_PATH in the generated file...\n\n") - return "UNKNOWN_PACKAGE_PATH" - } - return filepath.ToSlash(paths[len(paths)-1]) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/help_command.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/help_command.go deleted file mode 100644 index a42d4f8..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/help_command.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "flag" - "fmt" -) - -func BuildHelpCommand() *Command { - return &Command{ - Name: "help", - FlagSet: flag.NewFlagSet("help", flag.ExitOnError), - UsageCommand: "ginkgo help ", - Usage: []string{ - "Print usage information. If a command is passed in, print usage information just for that command.", - }, - Command: printHelp, - } -} - -func printHelp(args []string, additionalArgs []string) { - if len(args) == 0 { - usage() - } else { - command, found := commandMatching(args[0]) - if !found { - complainAndQuit(fmt.Sprintf("Unknown command: %s", args[0])) - } - - usageForCommand(command, true) - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/interrupthandler/interrupt_handler.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/interrupthandler/interrupt_handler.go deleted file mode 100644 index c15db0b..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/interrupthandler/interrupt_handler.go +++ /dev/null @@ -1,52 +0,0 @@ -package interrupthandler - -import ( - "os" - "os/signal" - "sync" - "syscall" -) - -type InterruptHandler struct { - interruptCount int - lock *sync.Mutex - C chan bool -} - -func NewInterruptHandler() *InterruptHandler { - h := &InterruptHandler{ - lock: &sync.Mutex{}, - C: make(chan bool, 0), - } - - go h.handleInterrupt() - SwallowSigQuit() - - return h -} - -func (h *InterruptHandler) WasInterrupted() bool { - h.lock.Lock() - defer h.lock.Unlock() - - return h.interruptCount > 0 -} - -func (h *InterruptHandler) handleInterrupt() { - c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt, syscall.SIGTERM) - - <-c - signal.Stop(c) - - h.lock.Lock() - h.interruptCount++ - if h.interruptCount == 1 { - close(h.C) - } else if h.interruptCount > 5 { - os.Exit(1) - } - h.lock.Unlock() - - go h.handleInterrupt() -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/interrupthandler/sigquit_swallower_unix.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/interrupthandler/sigquit_swallower_unix.go deleted file mode 100644 index 14c9421..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/interrupthandler/sigquit_swallower_unix.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build freebsd openbsd netbsd dragonfly darwin linux - -package interrupthandler - -import ( - "os" - "os/signal" - "syscall" -) - -func SwallowSigQuit() { - c := make(chan os.Signal, 1024) - signal.Notify(c, syscall.SIGQUIT) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/interrupthandler/sigquit_swallower_windows.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/interrupthandler/sigquit_swallower_windows.go deleted file mode 100644 index 7f4a50e..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/interrupthandler/sigquit_swallower_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build windows - -package interrupthandler - -func SwallowSigQuit() { - //noop -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/main.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/main.go deleted file mode 100644 index b031b80..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/main.go +++ /dev/null @@ -1,291 +0,0 @@ -/* -The Ginkgo CLI - -The Ginkgo CLI is fully documented [here](http://onsi.github.io/ginkgo/#the_ginkgo_cli) - -You can also learn more by running: - - ginkgo help - -Here are some of the more commonly used commands: - -To install: - - go install github.com/onsi/ginkgo/ginkgo - -To run tests: - - ginkgo - -To run tests in all subdirectories: - - ginkgo -r - -To run tests in particular packages: - - ginkgo /path/to/package /path/to/another/package - -To pass arguments/flags to your tests: - - ginkgo -- - -To run tests in parallel - - ginkgo -p - -this will automatically detect the optimal number of nodes to use. Alternatively, you can specify the number of nodes with: - - ginkgo -nodes=N - -(note that you don't need to provide -p in this case). - -By default the Ginkgo CLI will spin up a server that the individual test processes send test output to. The CLI aggregates this output and then presents coherent test output, one test at a time, as each test completes. -An alternative is to have the parallel nodes run and stream interleaved output back. This useful for debugging, particularly in contexts where tests hang/fail to start. To get this interleaved output: - - ginkgo -nodes=N -stream=true - -On windows, the default value for stream is true. - -By default, when running multiple tests (with -r or a list of packages) Ginkgo will abort when a test fails. To have Ginkgo run subsequent test suites instead you can: - - ginkgo -keepGoing - -To monitor packages and rerun tests when changes occur: - - ginkgo watch <-r> - -passing `ginkgo watch` the `-r` flag will recursively detect all test suites under the current directory and monitor them. -`watch` does not detect *new* packages. Moreover, changes in package X only rerun the tests for package X, tests for packages -that depend on X are not rerun. - -[OSX & Linux only] To receive (desktop) notifications when a test run completes: - - ginkgo -notify - -this is particularly useful with `ginkgo watch`. Notifications are currently only supported on OS X and require that you `brew install terminal-notifier` - -Sometimes (to suss out race conditions/flakey tests, for example) you want to keep running a test suite until it fails. You can do this with: - - ginkgo -untilItFails - -To bootstrap a test suite: - - ginkgo bootstrap - -To generate a test file: - - ginkgo generate - -To bootstrap/generate test files without using "." imports: - - ginkgo bootstrap --nodot - ginkgo generate --nodot - -this will explicitly export all the identifiers in Ginkgo and Gomega allowing you to rename them to avoid collisions. When you pull to the latest Ginkgo/Gomega you'll want to run - - ginkgo nodot - -to refresh this list and pull in any new identifiers. In particular, this will pull in any new Gomega matchers that get added. - -To convert an existing XUnit style test suite to a Ginkgo-style test suite: - - ginkgo convert . - -To unfocus tests: - - ginkgo unfocus - -or - - ginkgo blur - -To compile a test suite: - - ginkgo build - -will output an executable file named `package.test`. This can be run directly or by invoking - - ginkgo - -To print out Ginkgo's version: - - ginkgo version - -To get more help: - - ginkgo help -*/ -package main - -import ( - "flag" - "fmt" - "os" - "os/exec" - "strings" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/ginkgo/testsuite" -) - -const greenColor = "\x1b[32m" -const redColor = "\x1b[91m" -const defaultStyle = "\x1b[0m" -const lightGrayColor = "\x1b[37m" - -type Command struct { - Name string - AltName string - FlagSet *flag.FlagSet - Usage []string - UsageCommand string - Command func(args []string, additionalArgs []string) - SuppressFlagDocumentation bool - FlagDocSubstitute []string -} - -func (c *Command) Matches(name string) bool { - return c.Name == name || (c.AltName != "" && c.AltName == name) -} - -func (c *Command) Run(args []string, additionalArgs []string) { - c.FlagSet.Parse(args) - c.Command(c.FlagSet.Args(), additionalArgs) -} - -var DefaultCommand *Command -var Commands []*Command - -func init() { - DefaultCommand = BuildRunCommand() - Commands = append(Commands, BuildWatchCommand()) - Commands = append(Commands, BuildBuildCommand()) - Commands = append(Commands, BuildBootstrapCommand()) - Commands = append(Commands, BuildGenerateCommand()) - Commands = append(Commands, BuildNodotCommand()) - Commands = append(Commands, BuildConvertCommand()) - Commands = append(Commands, BuildUnfocusCommand()) - Commands = append(Commands, BuildVersionCommand()) - Commands = append(Commands, BuildHelpCommand()) -} - -func main() { - args := []string{} - additionalArgs := []string{} - - foundDelimiter := false - - for _, arg := range os.Args[1:] { - if !foundDelimiter { - if arg == "--" { - foundDelimiter = true - continue - } - } - - if foundDelimiter { - additionalArgs = append(additionalArgs, arg) - } else { - args = append(args, arg) - } - } - - if len(args) > 0 { - commandToRun, found := commandMatching(args[0]) - if found { - commandToRun.Run(args[1:], additionalArgs) - return - } - } - - DefaultCommand.Run(args, additionalArgs) -} - -func commandMatching(name string) (*Command, bool) { - for _, command := range Commands { - if command.Matches(name) { - return command, true - } - } - return nil, false -} - -func usage() { - fmt.Fprintf(os.Stderr, "Ginkgo Version %s\n\n", config.VERSION) - usageForCommand(DefaultCommand, false) - for _, command := range Commands { - fmt.Fprintf(os.Stderr, "\n") - usageForCommand(command, false) - } -} - -func usageForCommand(command *Command, longForm bool) { - fmt.Fprintf(os.Stderr, "%s\n%s\n", command.UsageCommand, strings.Repeat("-", len(command.UsageCommand))) - fmt.Fprintf(os.Stderr, "%s\n", strings.Join(command.Usage, "\n")) - if command.SuppressFlagDocumentation && !longForm { - fmt.Fprintf(os.Stderr, "%s\n", strings.Join(command.FlagDocSubstitute, "\n ")) - } else { - command.FlagSet.PrintDefaults() - } -} - -func complainAndQuit(complaint string) { - fmt.Fprintf(os.Stderr, "%s\nFor usage instructions:\n\tginkgo help\n", complaint) - os.Exit(1) -} - -func findSuites(args []string, recurse bool, skipPackage string, allowPrecompiled bool) ([]testsuite.TestSuite, []string) { - suites := []testsuite.TestSuite{} - - if len(args) > 0 { - for _, arg := range args { - if allowPrecompiled { - suite, err := testsuite.PrecompiledTestSuite(arg) - if err == nil { - suites = append(suites, suite) - continue - } - } - suites = append(suites, testsuite.SuitesInDir(arg, recurse)...) - } - } else { - suites = testsuite.SuitesInDir(".", recurse) - } - - skippedPackages := []string{} - if skipPackage != "" { - skipFilters := strings.Split(skipPackage, ",") - filteredSuites := []testsuite.TestSuite{} - for _, suite := range suites { - skip := false - for _, skipFilter := range skipFilters { - if strings.Contains(suite.Path, skipFilter) { - skip = true - break - } - } - if skip { - skippedPackages = append(skippedPackages, suite.Path) - } else { - filteredSuites = append(filteredSuites, suite) - } - } - suites = filteredSuites - } - - return suites, skippedPackages -} - -func goFmt(path string) { - err := exec.Command("go", "fmt", path).Run() - if err != nil { - complainAndQuit("Could not fmt: " + err.Error()) - } -} - -func pluralizedWord(singular, plural string, count int) string { - if count == 1 { - return singular - } - return plural -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot.go deleted file mode 100644 index 3f7237c..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot.go +++ /dev/null @@ -1,194 +0,0 @@ -package nodot - -import ( - "fmt" - "go/ast" - "go/build" - "go/parser" - "go/token" - "path/filepath" - "strings" -) - -func ApplyNoDot(data []byte) ([]byte, error) { - sections, err := generateNodotSections() - if err != nil { - return nil, err - } - - for _, section := range sections { - data = section.createOrUpdateIn(data) - } - - return data, nil -} - -type nodotSection struct { - name string - pkg string - declarations []string - types []string -} - -func (s nodotSection) createOrUpdateIn(data []byte) []byte { - renames := map[string]string{} - - contents := string(data) - - lines := strings.Split(contents, "\n") - - comment := "// Declarations for " + s.name - - newLines := []string{} - for _, line := range lines { - if line == comment { - continue - } - - words := strings.Split(line, " ") - lastWord := words[len(words)-1] - - if s.containsDeclarationOrType(lastWord) { - renames[lastWord] = words[1] - continue - } - - newLines = append(newLines, line) - } - - if len(newLines[len(newLines)-1]) > 0 { - newLines = append(newLines, "") - } - - newLines = append(newLines, comment) - - for _, typ := range s.types { - name, ok := renames[s.prefix(typ)] - if !ok { - name = typ - } - newLines = append(newLines, fmt.Sprintf("type %s %s", name, s.prefix(typ))) - } - - for _, decl := range s.declarations { - name, ok := renames[s.prefix(decl)] - if !ok { - name = decl - } - newLines = append(newLines, fmt.Sprintf("var %s = %s", name, s.prefix(decl))) - } - - newLines = append(newLines, "") - - newContents := strings.Join(newLines, "\n") - - return []byte(newContents) -} - -func (s nodotSection) prefix(declOrType string) string { - return s.pkg + "." + declOrType -} - -func (s nodotSection) containsDeclarationOrType(word string) bool { - for _, declaration := range s.declarations { - if s.prefix(declaration) == word { - return true - } - } - - for _, typ := range s.types { - if s.prefix(typ) == word { - return true - } - } - - return false -} - -func generateNodotSections() ([]nodotSection, error) { - sections := []nodotSection{} - - declarations, err := getExportedDeclerationsForPackage("github.com/onsi/ginkgo", "ginkgo_dsl.go", "GINKGO_VERSION", "GINKGO_PANIC") - if err != nil { - return nil, err - } - sections = append(sections, nodotSection{ - name: "Ginkgo DSL", - pkg: "ginkgo", - declarations: declarations, - types: []string{"Done", "Benchmarker"}, - }) - - declarations, err = getExportedDeclerationsForPackage("github.com/onsi/gomega", "gomega_dsl.go", "GOMEGA_VERSION") - if err != nil { - return nil, err - } - sections = append(sections, nodotSection{ - name: "Gomega DSL", - pkg: "gomega", - declarations: declarations, - }) - - declarations, err = getExportedDeclerationsForPackage("github.com/onsi/gomega", "matchers.go") - if err != nil { - return nil, err - } - sections = append(sections, nodotSection{ - name: "Gomega Matchers", - pkg: "gomega", - declarations: declarations, - }) - - return sections, nil -} - -func getExportedDeclerationsForPackage(pkgPath string, filename string, blacklist ...string) ([]string, error) { - pkg, err := build.Import(pkgPath, ".", 0) - if err != nil { - return []string{}, err - } - - declarations, err := getExportedDeclarationsForFile(filepath.Join(pkg.Dir, filename)) - if err != nil { - return []string{}, err - } - - blacklistLookup := map[string]bool{} - for _, declaration := range blacklist { - blacklistLookup[declaration] = true - } - - filteredDeclarations := []string{} - for _, declaration := range declarations { - if blacklistLookup[declaration] { - continue - } - filteredDeclarations = append(filteredDeclarations, declaration) - } - - return filteredDeclarations, nil -} - -func getExportedDeclarationsForFile(path string) ([]string, error) { - fset := token.NewFileSet() - tree, err := parser.ParseFile(fset, path, nil, 0) - if err != nil { - return []string{}, err - } - - declarations := []string{} - ast.FileExports(tree) - for _, decl := range tree.Decls { - switch x := decl.(type) { - case *ast.GenDecl: - switch s := x.Specs[0].(type) { - case *ast.ValueSpec: - declarations = append(declarations, s.Names[0].Name) - } - case *ast.FuncDecl: - declarations = append(declarations, x.Name.Name) - } - } - - return declarations, nil -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_suite_test.go deleted file mode 100644 index ca4613e..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_suite_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package nodot_test - -import ( - "github.com/onsi/ginkgo" - "github.com/onsi/gomega" - - "testing" -) - -func TestNodot(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Nodot Suite") -} - -// Declarations for Ginkgo DSL -type Done ginkgo.Done -type Benchmarker ginkgo.Benchmarker - -var GinkgoWriter = ginkgo.GinkgoWriter -var GinkgoParallelNode = ginkgo.GinkgoParallelNode -var GinkgoT = ginkgo.GinkgoT -var CurrentGinkgoTestDescription = ginkgo.CurrentGinkgoTestDescription -var RunSpecs = ginkgo.RunSpecs -var RunSpecsWithDefaultAndCustomReporters = ginkgo.RunSpecsWithDefaultAndCustomReporters -var RunSpecsWithCustomReporters = ginkgo.RunSpecsWithCustomReporters -var Fail = ginkgo.Fail -var GinkgoRecover = ginkgo.GinkgoRecover -var Describe = ginkgo.Describe -var FDescribe = ginkgo.FDescribe -var PDescribe = ginkgo.PDescribe -var XDescribe = ginkgo.XDescribe -var Context = ginkgo.Context -var FContext = ginkgo.FContext -var PContext = ginkgo.PContext -var XContext = ginkgo.XContext -var It = ginkgo.It -var FIt = ginkgo.FIt -var PIt = ginkgo.PIt -var XIt = ginkgo.XIt -var Measure = ginkgo.Measure -var FMeasure = ginkgo.FMeasure -var PMeasure = ginkgo.PMeasure -var XMeasure = ginkgo.XMeasure -var BeforeSuite = ginkgo.BeforeSuite -var AfterSuite = ginkgo.AfterSuite -var SynchronizedBeforeSuite = ginkgo.SynchronizedBeforeSuite -var SynchronizedAfterSuite = ginkgo.SynchronizedAfterSuite -var BeforeEach = ginkgo.BeforeEach -var JustBeforeEach = ginkgo.JustBeforeEach -var AfterEach = ginkgo.AfterEach - -// Declarations for Gomega DSL -var RegisterFailHandler = gomega.RegisterFailHandler -var RegisterTestingT = gomega.RegisterTestingT -var InterceptGomegaFailures = gomega.InterceptGomegaFailures -var Ω = gomega.Ω -var Expect = gomega.Expect -var ExpectWithOffset = gomega.ExpectWithOffset -var Eventually = gomega.Eventually -var EventuallyWithOffset = gomega.EventuallyWithOffset -var Consistently = gomega.Consistently -var ConsistentlyWithOffset = gomega.ConsistentlyWithOffset -var SetDefaultEventuallyTimeout = gomega.SetDefaultEventuallyTimeout -var SetDefaultEventuallyPollingInterval = gomega.SetDefaultEventuallyPollingInterval -var SetDefaultConsistentlyDuration = gomega.SetDefaultConsistentlyDuration -var SetDefaultConsistentlyPollingInterval = gomega.SetDefaultConsistentlyPollingInterval - -// Declarations for Gomega Matchers -var Equal = gomega.Equal -var BeEquivalentTo = gomega.BeEquivalentTo -var BeNil = gomega.BeNil -var BeTrue = gomega.BeTrue -var BeFalse = gomega.BeFalse -var HaveOccurred = gomega.HaveOccurred -var MatchError = gomega.MatchError -var BeClosed = gomega.BeClosed -var Receive = gomega.Receive -var MatchRegexp = gomega.MatchRegexp -var ContainSubstring = gomega.ContainSubstring -var MatchJSON = gomega.MatchJSON -var BeEmpty = gomega.BeEmpty -var HaveLen = gomega.HaveLen -var BeZero = gomega.BeZero -var ContainElement = gomega.ContainElement -var ConsistOf = gomega.ConsistOf -var HaveKey = gomega.HaveKey -var HaveKeyWithValue = gomega.HaveKeyWithValue -var BeNumerically = gomega.BeNumerically -var BeTemporally = gomega.BeTemporally -var BeAssignableToTypeOf = gomega.BeAssignableToTypeOf -var Panic = gomega.Panic diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_test.go deleted file mode 100644 index 37260a8..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package nodot_test - -import ( - . "github.com/onsi/ginkgo/ginkgo/nodot" - "strings" -) - -var _ = Describe("ApplyNoDot", func() { - var result string - - apply := func(input string) string { - output, err := ApplyNoDot([]byte(input)) - Ω(err).ShouldNot(HaveOccurred()) - return string(output) - } - - Context("when no declarations have been imported yet", func() { - BeforeEach(func() { - result = apply("") - }) - - It("should add headings for the various declarations", func() { - Ω(result).Should(ContainSubstring("// Declarations for Ginkgo DSL")) - Ω(result).Should(ContainSubstring("// Declarations for Gomega DSL")) - Ω(result).Should(ContainSubstring("// Declarations for Gomega Matchers")) - }) - - It("should import Ginkgo's declarations", func() { - Ω(result).Should(ContainSubstring("var It = ginkgo.It")) - Ω(result).Should(ContainSubstring("var XDescribe = ginkgo.XDescribe")) - }) - - It("should import Ginkgo's types", func() { - Ω(result).Should(ContainSubstring("type Done ginkgo.Done")) - Ω(result).Should(ContainSubstring("type Benchmarker ginkgo.Benchmarker")) - Ω(strings.Count(result, "type ")).Should(Equal(2)) - }) - - It("should import Gomega's DSL and matchers", func() { - Ω(result).Should(ContainSubstring("var Ω = gomega.Ω")) - Ω(result).Should(ContainSubstring("var ContainSubstring = gomega.ContainSubstring")) - Ω(result).Should(ContainSubstring("var Equal = gomega.Equal")) - }) - - It("should not import blacklisted things", func() { - Ω(result).ShouldNot(ContainSubstring("GINKGO_VERSION")) - Ω(result).ShouldNot(ContainSubstring("GINKGO_PANIC")) - Ω(result).ShouldNot(ContainSubstring("GOMEGA_VERSION")) - }) - }) - - It("should be idempotent (module empty lines - go fmt can fix those for us)", func() { - first := apply("") - second := apply(first) - first = strings.Trim(first, "\n") - second = strings.Trim(second, "\n") - Ω(first).Should(Equal(second)) - }) - - It("should not mess with other things in the input", func() { - result = apply("var MyThing = SomethingThatsMine") - Ω(result).Should(ContainSubstring("var MyThing = SomethingThatsMine")) - }) - - Context("when the user has redefined a name", func() { - It("should honor the redefinition", func() { - result = apply(` -var _ = gomega.Ω -var When = ginkgo.It - `) - - Ω(result).Should(ContainSubstring("var _ = gomega.Ω")) - Ω(result).ShouldNot(ContainSubstring("var Ω = gomega.Ω")) - - Ω(result).Should(ContainSubstring("var When = ginkgo.It")) - Ω(result).ShouldNot(ContainSubstring("var It = ginkgo.It")) - - Ω(result).Should(ContainSubstring("var Context = ginkgo.Context")) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot_command.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot_command.go deleted file mode 100644 index e1a2e13..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot_command.go +++ /dev/null @@ -1,74 +0,0 @@ -package main - -import ( - "bufio" - "flag" - "github.com/onsi/ginkgo/ginkgo/nodot" - "io/ioutil" - "os" - "path/filepath" - "regexp" -) - -func BuildNodotCommand() *Command { - return &Command{ - Name: "nodot", - FlagSet: flag.NewFlagSet("bootstrap", flag.ExitOnError), - UsageCommand: "ginkgo nodot", - Usage: []string{ - "Update the nodot declarations in your test suite", - "Any missing declarations (from, say, a recently added matcher) will be added to your bootstrap file.", - "If you've renamed a declaration, that name will be honored and not overwritten.", - }, - Command: updateNodot, - } -} - -func updateNodot(args []string, additionalArgs []string) { - suiteFile, perm := findSuiteFile() - - data, err := ioutil.ReadFile(suiteFile) - if err != nil { - complainAndQuit("Failed to update nodot declarations: " + err.Error()) - } - - content, err := nodot.ApplyNoDot(data) - if err != nil { - complainAndQuit("Failed to update nodot declarations: " + err.Error()) - } - ioutil.WriteFile(suiteFile, content, perm) - - goFmt(suiteFile) -} - -func findSuiteFile() (string, os.FileMode) { - workingDir, err := os.Getwd() - if err != nil { - complainAndQuit("Could not find suite file for nodot: " + err.Error()) - } - - files, err := ioutil.ReadDir(workingDir) - if err != nil { - complainAndQuit("Could not find suite file for nodot: " + err.Error()) - } - - re := regexp.MustCompile(`RunSpecs\(|RunSpecsWithDefaultAndCustomReporters\(|RunSpecsWithCustomReporters\(`) - - for _, file := range files { - if file.IsDir() { - continue - } - path := filepath.Join(workingDir, file.Name()) - f, err := os.Open(path) - if err != nil { - complainAndQuit("Could not find suite file for nodot: " + err.Error()) - } - if re.MatchReader(bufio.NewReader(f)) { - return path, file.Mode() - } - } - - complainAndQuit("Could not find a suite file for nodot: you need a bootstrap file that call's Ginkgo's RunSpecs() command.\nTry running ginkgo bootstrap first.") - - return "", 0 -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/notifications.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/notifications.go deleted file mode 100644 index 31641ce..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/notifications.go +++ /dev/null @@ -1,101 +0,0 @@ -package main - -import ( - "fmt" - "os" - "os/exec" - "runtime" - - "github.com/onsi/ginkgo/ginkgo/testsuite" -) - -type Notifier struct { - commandFlags *RunWatchAndBuildCommandFlags -} - -func NewNotifier(commandFlags *RunWatchAndBuildCommandFlags) *Notifier { - return &Notifier{ - commandFlags: commandFlags, - } -} - -func (n *Notifier) VerifyNotificationsAreAvailable() { - if n.commandFlags.Notify { - onLinux := (runtime.GOOS == "linux") - onOSX := (runtime.GOOS == "darwin") - if onOSX { - - _, err := exec.LookPath("terminal-notifier") - if err != nil { - fmt.Printf(`--notify requires terminal-notifier, which you don't seem to have installed. - -OSX: - -To remedy this: - - brew install terminal-notifier - -To learn more about terminal-notifier: - - https://github.com/alloy/terminal-notifier -`) - os.Exit(1) - } - - } else if onLinux { - - _, err := exec.LookPath("notify-send") - if err != nil { - fmt.Printf(`--notify requires terminal-notifier or notify-send, which you don't seem to have installed. - -Linux: - -Download and install notify-send for your distribution -`) - os.Exit(1) - } - - } - } -} - -func (n *Notifier) SendSuiteCompletionNotification(suite testsuite.TestSuite, suitePassed bool) { - if suitePassed { - n.SendNotification("Ginkgo [PASS]", fmt.Sprintf(`Test suite for "%s" passed.`, suite.PackageName)) - } else { - n.SendNotification("Ginkgo [FAIL]", fmt.Sprintf(`Test suite for "%s" failed.`, suite.PackageName)) - } -} - -func (n *Notifier) SendNotification(title string, subtitle string) { - - if n.commandFlags.Notify { - onLinux := (runtime.GOOS == "linux") - onOSX := (runtime.GOOS == "darwin") - - if onOSX { - - _, err := exec.LookPath("terminal-notifier") - if err == nil { - args := []string{"-title", title, "-subtitle", subtitle, "-group", "com.onsi.ginkgo"} - terminal := os.Getenv("TERM_PROGRAM") - if terminal == "iTerm.app" { - args = append(args, "-activate", "com.googlecode.iterm2") - } else if terminal == "Apple_Terminal" { - args = append(args, "-activate", "com.apple.Terminal") - } - - exec.Command("terminal-notifier", args...).Run() - } - - } else if onLinux { - - _, err := exec.LookPath("notify-send") - if err == nil { - args := []string{"-a", "ginkgo", title, subtitle} - exec.Command("notify-send", args...).Run() - } - - } - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/run_command.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/run_command.go deleted file mode 100644 index c5cf277..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/run_command.go +++ /dev/null @@ -1,192 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "math/rand" - "os" - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/ginkgo/interrupthandler" - "github.com/onsi/ginkgo/ginkgo/testrunner" - "github.com/onsi/ginkgo/types" -) - -func BuildRunCommand() *Command { - commandFlags := NewRunCommandFlags(flag.NewFlagSet("ginkgo", flag.ExitOnError)) - notifier := NewNotifier(commandFlags) - interruptHandler := interrupthandler.NewInterruptHandler() - runner := &SpecRunner{ - commandFlags: commandFlags, - notifier: notifier, - interruptHandler: interruptHandler, - suiteRunner: NewSuiteRunner(notifier, interruptHandler), - } - - return &Command{ - Name: "", - FlagSet: commandFlags.FlagSet, - UsageCommand: "ginkgo -- ", - Usage: []string{ - "Run the tests in the passed in (or the package in the current directory if left blank).", - "Any arguments after -- will be passed to the test.", - "Accepts the following flags:", - }, - Command: runner.RunSpecs, - } -} - -type SpecRunner struct { - commandFlags *RunWatchAndBuildCommandFlags - notifier *Notifier - interruptHandler *interrupthandler.InterruptHandler - suiteRunner *SuiteRunner -} - -func (r *SpecRunner) RunSpecs(args []string, additionalArgs []string) { - r.commandFlags.computeNodes() - r.notifier.VerifyNotificationsAreAvailable() - - suites, skippedPackages := findSuites(args, r.commandFlags.Recurse, r.commandFlags.SkipPackage, true) - if len(skippedPackages) > 0 { - fmt.Println("Will skip:") - for _, skippedPackage := range skippedPackages { - fmt.Println(" " + skippedPackage) - } - } - - if len(skippedPackages) > 0 && len(suites) == 0 { - fmt.Println("All tests skipped! Exiting...") - os.Exit(0) - } - - if len(suites) == 0 { - complainAndQuit("Found no test suites") - } - - r.ComputeSuccinctMode(len(suites)) - - t := time.Now() - - runners := []*testrunner.TestRunner{} - for _, suite := range suites { - runners = append(runners, testrunner.New(suite, r.commandFlags.NumCPU, r.commandFlags.ParallelStream, r.commandFlags.Race, r.commandFlags.Cover, r.commandFlags.CoverPkg, r.commandFlags.Tags, additionalArgs)) - } - - numSuites := 0 - runResult := testrunner.PassingRunResult() - if r.commandFlags.UntilItFails { - iteration := 0 - for { - r.UpdateSeed() - randomizedRunners := r.randomizeOrder(runners) - runResult, numSuites = r.suiteRunner.RunSuites(randomizedRunners, r.commandFlags.NumCompilers, r.commandFlags.KeepGoing, nil) - iteration++ - - if r.interruptHandler.WasInterrupted() { - break - } - - if runResult.Passed { - fmt.Printf("\nAll tests passed...\nWill keep running them until they fail.\nThis was attempt #%d\n%s\n", iteration, orcMessage(iteration)) - } else { - fmt.Printf("\nTests failed on attempt #%d\n\n", iteration) - break - } - } - } else { - randomizedRunners := r.randomizeOrder(runners) - runResult, numSuites = r.suiteRunner.RunSuites(randomizedRunners, r.commandFlags.NumCompilers, r.commandFlags.KeepGoing, nil) - } - - for _, runner := range runners { - runner.CleanUp() - } - - fmt.Printf("\nGinkgo ran %d %s in %s\n", numSuites, pluralizedWord("suite", "suites", numSuites), time.Since(t)) - - if runResult.Passed { - if runResult.HasProgrammaticFocus { - fmt.Printf("Test Suite Passed\n") - fmt.Printf("Detected Programmatic Focus - setting exit status to %d\n", types.GINKGO_FOCUS_EXIT_CODE) - os.Exit(types.GINKGO_FOCUS_EXIT_CODE) - } else { - fmt.Printf("Test Suite Passed\n") - os.Exit(0) - } - } else { - fmt.Printf("Test Suite Failed\n") - os.Exit(1) - } -} - -func (r *SpecRunner) ComputeSuccinctMode(numSuites int) { - if config.DefaultReporterConfig.Verbose { - config.DefaultReporterConfig.Succinct = false - return - } - - if numSuites == 1 { - return - } - - if numSuites > 1 && !r.commandFlags.wasSet("succinct") { - config.DefaultReporterConfig.Succinct = true - } -} - -func (r *SpecRunner) UpdateSeed() { - if !r.commandFlags.wasSet("seed") { - config.GinkgoConfig.RandomSeed = time.Now().Unix() - } -} - -func (r *SpecRunner) randomizeOrder(runners []*testrunner.TestRunner) []*testrunner.TestRunner { - if !r.commandFlags.RandomizeSuites { - return runners - } - - if len(runners) <= 1 { - return runners - } - - randomizedRunners := make([]*testrunner.TestRunner, len(runners)) - randomizer := rand.New(rand.NewSource(config.GinkgoConfig.RandomSeed)) - permutation := randomizer.Perm(len(runners)) - for i, j := range permutation { - randomizedRunners[i] = runners[j] - } - return randomizedRunners -} - -func orcMessage(iteration int) string { - if iteration < 10 { - return "" - } else if iteration < 30 { - return []string{ - "If at first you succeed...", - "...try, try again.", - "Looking good!", - "Still good...", - "I think your tests are fine....", - "Yep, still passing", - "Here we go again...", - "Even the gophers are getting bored", - "Did you try -race?", - "Maybe you should stop now?", - "I'm getting tired...", - "What if I just made you a sandwich?", - "Hit ^C, hit ^C, please hit ^C", - "Make it stop. Please!", - "Come on! Enough is enough!", - "Dave, this conversation can serve no purpose anymore. Goodbye.", - "Just what do you think you're doing, Dave? ", - "I, Sisyphus", - "Insanity: doing the same thing over and over again and expecting different results. -Einstein", - "I guess Einstein never tried to churn butter", - }[iteration-10] + "\n" - } else { - return "No, seriously... you can probably stop now.\n" - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/run_watch_and_build_command_flags.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/run_watch_and_build_command_flags.go deleted file mode 100644 index 400bb54..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/run_watch_and_build_command_flags.go +++ /dev/null @@ -1,119 +0,0 @@ -package main - -import ( - "flag" - "runtime" - - "github.com/onsi/ginkgo/config" -) - -type RunWatchAndBuildCommandFlags struct { - Recurse bool - Race bool - Cover bool - CoverPkg string - SkipPackage string - Tags string - - //for run and watch commands - NumCPU int - NumCompilers int - ParallelStream bool - Notify bool - AutoNodes bool - - //only for run command - KeepGoing bool - UntilItFails bool - RandomizeSuites bool - - //only for watch command - Depth int - - FlagSet *flag.FlagSet -} - -const runMode = 1 -const watchMode = 2 -const buildMode = 3 - -func NewRunCommandFlags(flagSet *flag.FlagSet) *RunWatchAndBuildCommandFlags { - c := &RunWatchAndBuildCommandFlags{ - FlagSet: flagSet, - } - c.flags(runMode) - return c -} - -func NewWatchCommandFlags(flagSet *flag.FlagSet) *RunWatchAndBuildCommandFlags { - c := &RunWatchAndBuildCommandFlags{ - FlagSet: flagSet, - } - c.flags(watchMode) - return c -} - -func NewBuildCommandFlags(flagSet *flag.FlagSet) *RunWatchAndBuildCommandFlags { - c := &RunWatchAndBuildCommandFlags{ - FlagSet: flagSet, - } - c.flags(buildMode) - return c -} - -func (c *RunWatchAndBuildCommandFlags) wasSet(flagName string) bool { - wasSet := false - c.FlagSet.Visit(func(f *flag.Flag) { - if f.Name == flagName { - wasSet = true - } - }) - - return wasSet -} - -func (c *RunWatchAndBuildCommandFlags) computeNodes() { - if c.wasSet("nodes") { - return - } - if c.AutoNodes { - switch n := runtime.NumCPU(); { - case n <= 4: - c.NumCPU = n - default: - c.NumCPU = n - 1 - } - } -} - -func (c *RunWatchAndBuildCommandFlags) flags(mode int) { - onWindows := (runtime.GOOS == "windows") - - c.FlagSet.BoolVar(&(c.Recurse), "r", false, "Find and run test suites under the current directory recursively") - c.FlagSet.BoolVar(&(c.Race), "race", false, "Run tests with race detection enabled") - c.FlagSet.BoolVar(&(c.Cover), "cover", false, "Run tests with coverage analysis, will generate coverage profiles with the package name in the current directory") - c.FlagSet.StringVar(&(c.CoverPkg), "coverpkg", "", "Run tests with coverage on the given external modules") - c.FlagSet.StringVar(&(c.SkipPackage), "skipPackage", "", "A comma-separated list of package names to be skipped. If any part of the package's path matches, that package is ignored.") - c.FlagSet.StringVar(&(c.Tags), "tags", "", "A list of build tags to consider satisfied during the build") - - if mode == runMode || mode == watchMode { - config.Flags(c.FlagSet, "", false) - c.FlagSet.IntVar(&(c.NumCPU), "nodes", 1, "The number of parallel test nodes to run") - c.FlagSet.IntVar(&(c.NumCompilers), "compilers", 0, "The number of concurrent compilations to run (0 will autodetect)") - c.FlagSet.BoolVar(&(c.AutoNodes), "p", false, "Run in parallel with auto-detected number of nodes") - c.FlagSet.BoolVar(&(c.ParallelStream), "stream", onWindows, "stream parallel test output in real time: less coherent, but useful for debugging") - if !onWindows { - c.FlagSet.BoolVar(&(c.Notify), "notify", false, "Send desktop notifications when a test run completes") - } - } - - if mode == runMode { - c.FlagSet.BoolVar(&(c.KeepGoing), "keepGoing", false, "When true, failures from earlier test suites do not prevent later test suites from running") - c.FlagSet.BoolVar(&(c.UntilItFails), "untilItFails", false, "When true, Ginkgo will keep rerunning tests until a failure occurs") - c.FlagSet.BoolVar(&(c.RandomizeSuites), "randomizeSuites", false, "When true, Ginkgo will randomize the order in which test suites run") - } - - if mode == watchMode { - c.FlagSet.IntVar(&(c.Depth), "depth", 1, "Ginkgo will watch dependencies down to this depth in the dependency tree") - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/suite_runner.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/suite_runner.go deleted file mode 100644 index d134b96..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/suite_runner.go +++ /dev/null @@ -1,171 +0,0 @@ -package main - -import ( - "fmt" - "runtime" - "sync" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/ginkgo/interrupthandler" - "github.com/onsi/ginkgo/ginkgo/testrunner" - "github.com/onsi/ginkgo/ginkgo/testsuite" -) - -type compilationInput struct { - runner *testrunner.TestRunner - result chan compilationOutput -} - -type compilationOutput struct { - runner *testrunner.TestRunner - err error -} - -type SuiteRunner struct { - notifier *Notifier - interruptHandler *interrupthandler.InterruptHandler -} - -func NewSuiteRunner(notifier *Notifier, interruptHandler *interrupthandler.InterruptHandler) *SuiteRunner { - return &SuiteRunner{ - notifier: notifier, - interruptHandler: interruptHandler, - } -} - -func (r *SuiteRunner) compileInParallel(runners []*testrunner.TestRunner, numCompilers int, willCompile func(suite testsuite.TestSuite)) chan compilationOutput { - //we return this to the consumer, it will return each runner in order as it compiles - compilationOutputs := make(chan compilationOutput, len(runners)) - - //an array of channels - the nth runner's compilation output is sent to the nth channel in this array - //we read from these channels in order to ensure we run the suites in order - orderedCompilationOutputs := []chan compilationOutput{} - for _ = range runners { - orderedCompilationOutputs = append(orderedCompilationOutputs, make(chan compilationOutput, 1)) - } - - //we're going to spin up numCompilers compilers - they're going to run concurrently and will consume this channel - //we prefill the channel then close it, this ensures we compile things in the correct order - workPool := make(chan compilationInput, len(runners)) - for i, runner := range runners { - workPool <- compilationInput{runner, orderedCompilationOutputs[i]} - } - close(workPool) - - //pick a reasonable numCompilers - if numCompilers == 0 { - numCompilers = runtime.NumCPU() - } - - //a WaitGroup to help us wait for all compilers to shut down - wg := &sync.WaitGroup{} - wg.Add(numCompilers) - - //spin up the concurrent compilers - for i := 0; i < numCompilers; i++ { - go func() { - defer wg.Done() - for input := range workPool { - if r.interruptHandler.WasInterrupted() { - return - } - - if willCompile != nil { - willCompile(input.runner.Suite) - } - - //We retry because Go sometimes steps on itself when multiple compiles happen in parallel. This is ugly, but should help resolve flakiness... - var err error - retries := 0 - for retries <= 5 { - if r.interruptHandler.WasInterrupted() { - return - } - if err = input.runner.Compile(); err == nil { - break - } - retries++ - } - - input.result <- compilationOutput{input.runner, err} - } - }() - } - - //read from the compilation output channels *in order* and send them to the caller - //close the compilationOutputs channel to tell the caller we're done - go func() { - defer close(compilationOutputs) - for _, orderedCompilationOutput := range orderedCompilationOutputs { - select { - case compilationOutput := <-orderedCompilationOutput: - compilationOutputs <- compilationOutput - case <-r.interruptHandler.C: - //interrupt detected, wait for the compilers to shut down then bail - //this ensure we clean up after ourselves as we don't leave any compilation processes running - wg.Wait() - return - } - } - }() - - return compilationOutputs -} - -func (r *SuiteRunner) RunSuites(runners []*testrunner.TestRunner, numCompilers int, keepGoing bool, willCompile func(suite testsuite.TestSuite)) (testrunner.RunResult, int) { - runResult := testrunner.PassingRunResult() - - compilationOutputs := r.compileInParallel(runners, numCompilers, willCompile) - - numSuitesThatRan := 0 - suitesThatFailed := []testsuite.TestSuite{} - for compilationOutput := range compilationOutputs { - if compilationOutput.err != nil { - fmt.Print(compilationOutput.err.Error()) - } - numSuitesThatRan++ - suiteRunResult := testrunner.FailingRunResult() - if compilationOutput.err == nil { - suiteRunResult = compilationOutput.runner.Run() - } - r.notifier.SendSuiteCompletionNotification(compilationOutput.runner.Suite, suiteRunResult.Passed) - runResult = runResult.Merge(suiteRunResult) - if !suiteRunResult.Passed { - suitesThatFailed = append(suitesThatFailed, compilationOutput.runner.Suite) - if !keepGoing { - break - } - } - if numSuitesThatRan < len(runners) && !config.DefaultReporterConfig.Succinct { - fmt.Println("") - } - } - - if keepGoing && !runResult.Passed { - r.listFailedSuites(suitesThatFailed) - } - - return runResult, numSuitesThatRan -} - -func (r *SuiteRunner) listFailedSuites(suitesThatFailed []testsuite.TestSuite) { - fmt.Println("") - fmt.Println("There were failures detected in the following suites:") - - maxPackageNameLength := 0 - for _, suite := range suitesThatFailed { - if len(suite.PackageName) > maxPackageNameLength { - maxPackageNameLength = len(suite.PackageName) - } - } - - packageNameFormatter := fmt.Sprintf("%%%ds", maxPackageNameLength) - - for _, suite := range suitesThatFailed { - if config.DefaultReporterConfig.NoColor { - fmt.Printf("\t"+packageNameFormatter+" %s\n", suite.PackageName, suite.Path) - } else { - fmt.Printf("\t%s"+packageNameFormatter+"%s %s%s%s\n", redColor, suite.PackageName, defaultStyle, lightGrayColor, suite.Path, defaultStyle) - } - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testrunner/log_writer.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testrunner/log_writer.go deleted file mode 100644 index a73a6e3..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testrunner/log_writer.go +++ /dev/null @@ -1,52 +0,0 @@ -package testrunner - -import ( - "bytes" - "fmt" - "io" - "log" - "strings" - "sync" -) - -type logWriter struct { - buffer *bytes.Buffer - lock *sync.Mutex - log *log.Logger -} - -func newLogWriter(target io.Writer, node int) *logWriter { - return &logWriter{ - buffer: &bytes.Buffer{}, - lock: &sync.Mutex{}, - log: log.New(target, fmt.Sprintf("[%d] ", node), 0), - } -} - -func (w *logWriter) Write(data []byte) (n int, err error) { - w.lock.Lock() - defer w.lock.Unlock() - - w.buffer.Write(data) - contents := w.buffer.String() - - lines := strings.Split(contents, "\n") - for _, line := range lines[0 : len(lines)-1] { - w.log.Println(line) - } - - w.buffer.Reset() - w.buffer.Write([]byte(lines[len(lines)-1])) - return len(data), nil -} - -func (w *logWriter) Close() error { - w.lock.Lock() - defer w.lock.Unlock() - - if w.buffer.Len() > 0 { - w.log.Println(w.buffer.String()) - } - - return nil -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testrunner/run_result.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testrunner/run_result.go deleted file mode 100644 index 5d472ac..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testrunner/run_result.go +++ /dev/null @@ -1,27 +0,0 @@ -package testrunner - -type RunResult struct { - Passed bool - HasProgrammaticFocus bool -} - -func PassingRunResult() RunResult { - return RunResult{ - Passed: true, - HasProgrammaticFocus: false, - } -} - -func FailingRunResult() RunResult { - return RunResult{ - Passed: false, - HasProgrammaticFocus: false, - } -} - -func (r RunResult) Merge(o RunResult) RunResult { - return RunResult{ - Passed: r.Passed && o.Passed, - HasProgrammaticFocus: r.HasProgrammaticFocus || o.HasProgrammaticFocus, - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testrunner/test_runner.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testrunner/test_runner.go deleted file mode 100644 index 23bc518..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testrunner/test_runner.go +++ /dev/null @@ -1,393 +0,0 @@ -package testrunner - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "regexp" - "strconv" - "strings" - "syscall" - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/ginkgo/testsuite" - "github.com/onsi/ginkgo/internal/remote" - "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" -) - -type TestRunner struct { - Suite testsuite.TestSuite - - compiled bool - compilationTargetPath string - - numCPU int - parallelStream bool - race bool - cover bool - coverPkg string - tags string - additionalArgs []string -} - -func New(suite testsuite.TestSuite, numCPU int, parallelStream bool, race bool, cover bool, coverPkg string, tags string, additionalArgs []string) *TestRunner { - runner := &TestRunner{ - Suite: suite, - numCPU: numCPU, - parallelStream: parallelStream, - race: race, - cover: cover, - coverPkg: coverPkg, - tags: tags, - additionalArgs: additionalArgs, - } - - if !suite.Precompiled { - dir, err := ioutil.TempDir("", "ginkgo") - if err != nil { - panic(fmt.Sprintf("coulnd't create temporary directory... might be time to rm -rf:\n%s", err.Error())) - } - runner.compilationTargetPath = filepath.Join(dir, suite.PackageName+".test") - } - - return runner -} - -func (t *TestRunner) Compile() error { - return t.CompileTo(t.compilationTargetPath) -} - -func (t *TestRunner) CompileTo(path string) error { - if t.compiled { - return nil - } - - if t.Suite.Precompiled { - return nil - } - - args := []string{"test", "-c", "-i", "-o", path} - if t.race { - args = append(args, "-race") - } - if t.cover || t.coverPkg != "" { - args = append(args, "-cover", "-covermode=atomic") - } - if t.coverPkg != "" { - args = append(args, fmt.Sprintf("-coverpkg=%s", t.coverPkg)) - } - if t.tags != "" { - args = append(args, fmt.Sprintf("-tags=%s", t.tags)) - } - - cmd := exec.Command("go", args...) - - cmd.Dir = t.Suite.Path - - output, err := cmd.CombinedOutput() - - if err != nil { - fixedOutput := fixCompilationOutput(string(output), t.Suite.Path) - if len(output) > 0 { - return fmt.Errorf("Failed to compile %s:\n\n%s", t.Suite.PackageName, fixedOutput) - } - return fmt.Errorf("Failed to compile %s", t.Suite.PackageName) - } - - t.compiled = true - - return nil -} - -/* -go test -c -i spits package.test out into the cwd. there's no way to change this. - -to make sure it doesn't generate conflicting .test files in the cwd, Compile() must switch the cwd to the test package. - -unfortunately, this causes go test's compile output to be expressed *relative to the test package* instead of the cwd. - -this makes it hard to reason about what failed, and also prevents iterm's Cmd+click from working. - -fixCompilationOutput..... rewrites the output to fix the paths. - -yeah...... -*/ -func fixCompilationOutput(output string, relToPath string) string { - re := regexp.MustCompile(`^(\S.*\.go)\:\d+\:`) - lines := strings.Split(output, "\n") - for i, line := range lines { - indices := re.FindStringSubmatchIndex(line) - if len(indices) == 0 { - continue - } - - path := line[indices[2]:indices[3]] - path = filepath.Join(relToPath, path) - lines[i] = path + line[indices[3]:] - } - return strings.Join(lines, "\n") -} - -func (t *TestRunner) Run() RunResult { - if t.Suite.IsGinkgo { - if t.numCPU > 1 { - if t.parallelStream { - return t.runAndStreamParallelGinkgoSuite() - } else { - return t.runParallelGinkgoSuite() - } - } else { - return t.runSerialGinkgoSuite() - } - } else { - return t.runGoTestSuite() - } -} - -func (t *TestRunner) CleanUp() { - if t.Suite.Precompiled { - return - } - os.RemoveAll(filepath.Dir(t.compilationTargetPath)) -} - -func (t *TestRunner) runSerialGinkgoSuite() RunResult { - ginkgoArgs := config.BuildFlagArgs("ginkgo", config.GinkgoConfig, config.DefaultReporterConfig) - return t.run(t.cmd(ginkgoArgs, os.Stdout, 1), nil) -} - -func (t *TestRunner) runGoTestSuite() RunResult { - return t.run(t.cmd([]string{"-test.v"}, os.Stdout, 1), nil) -} - -func (t *TestRunner) runAndStreamParallelGinkgoSuite() RunResult { - completions := make(chan RunResult) - writers := make([]*logWriter, t.numCPU) - - server, err := remote.NewServer(t.numCPU) - if err != nil { - panic("Failed to start parallel spec server") - } - - server.Start() - defer server.Close() - - for cpu := 0; cpu < t.numCPU; cpu++ { - config.GinkgoConfig.ParallelNode = cpu + 1 - config.GinkgoConfig.ParallelTotal = t.numCPU - config.GinkgoConfig.SyncHost = server.Address() - - ginkgoArgs := config.BuildFlagArgs("ginkgo", config.GinkgoConfig, config.DefaultReporterConfig) - - writers[cpu] = newLogWriter(os.Stdout, cpu+1) - - cmd := t.cmd(ginkgoArgs, writers[cpu], cpu+1) - - server.RegisterAlive(cpu+1, func() bool { - if cmd.ProcessState == nil { - return true - } - return !cmd.ProcessState.Exited() - }) - - go t.run(cmd, completions) - } - - res := PassingRunResult() - - for cpu := 0; cpu < t.numCPU; cpu++ { - res = res.Merge(<-completions) - } - - for _, writer := range writers { - writer.Close() - } - - os.Stdout.Sync() - - if t.cover || t.coverPkg != "" { - t.combineCoverprofiles() - } - - return res -} - -func (t *TestRunner) runParallelGinkgoSuite() RunResult { - result := make(chan bool) - completions := make(chan RunResult) - writers := make([]*logWriter, t.numCPU) - reports := make([]*bytes.Buffer, t.numCPU) - - stenographer := stenographer.New(!config.DefaultReporterConfig.NoColor) - aggregator := remote.NewAggregator(t.numCPU, result, config.DefaultReporterConfig, stenographer) - - server, err := remote.NewServer(t.numCPU) - if err != nil { - panic("Failed to start parallel spec server") - } - server.RegisterReporters(aggregator) - server.Start() - defer server.Close() - - for cpu := 0; cpu < t.numCPU; cpu++ { - config.GinkgoConfig.ParallelNode = cpu + 1 - config.GinkgoConfig.ParallelTotal = t.numCPU - config.GinkgoConfig.SyncHost = server.Address() - config.GinkgoConfig.StreamHost = server.Address() - - ginkgoArgs := config.BuildFlagArgs("ginkgo", config.GinkgoConfig, config.DefaultReporterConfig) - - reports[cpu] = &bytes.Buffer{} - writers[cpu] = newLogWriter(reports[cpu], cpu+1) - - cmd := t.cmd(ginkgoArgs, writers[cpu], cpu+1) - - server.RegisterAlive(cpu+1, func() bool { - if cmd.ProcessState == nil { - return true - } - return !cmd.ProcessState.Exited() - }) - - go t.run(cmd, completions) - } - - res := PassingRunResult() - - for cpu := 0; cpu < t.numCPU; cpu++ { - res = res.Merge(<-completions) - } - - //all test processes are done, at this point - //we should be able to wait for the aggregator to tell us that it's done - - select { - case <-result: - fmt.Println("") - case <-time.After(time.Second): - //the aggregator never got back to us! something must have gone wrong - fmt.Println(` - ------------------------------------------------------------------- - | | - | Ginkgo timed out waiting for all parallel nodes to report back! | - | | - ------------------------------------------------------------------- -`) - - os.Stdout.Sync() - - for _, writer := range writers { - writer.Close() - } - - for _, report := range reports { - fmt.Print(report.String()) - } - - os.Stdout.Sync() - } - - if t.cover || t.coverPkg != "" { - t.combineCoverprofiles() - } - - return res -} - -func (t *TestRunner) cmd(ginkgoArgs []string, stream io.Writer, node int) *exec.Cmd { - args := []string{"--test.timeout=24h"} - if t.cover || t.coverPkg != "" { - coverprofile := "--test.coverprofile=" + t.Suite.PackageName + ".coverprofile" - if t.numCPU > 1 { - coverprofile = fmt.Sprintf("%s.%d", coverprofile, node) - } - args = append(args, coverprofile) - } - - args = append(args, ginkgoArgs...) - args = append(args, t.additionalArgs...) - - path := t.compilationTargetPath - if t.Suite.Precompiled { - path, _ = filepath.Abs(filepath.Join(t.Suite.Path, fmt.Sprintf("%s.test", t.Suite.PackageName))) - } - - cmd := exec.Command(path, args...) - - cmd.Dir = t.Suite.Path - cmd.Stderr = stream - cmd.Stdout = stream - - return cmd -} - -func (t *TestRunner) run(cmd *exec.Cmd, completions chan RunResult) RunResult { - var res RunResult - - defer func() { - if completions != nil { - completions <- res - } - }() - - err := cmd.Start() - if err != nil { - fmt.Printf("Failed to run test suite!\n\t%s", err.Error()) - return res - } - - cmd.Wait() - exitStatus := cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus() - res.Passed = (exitStatus == 0) || (exitStatus == types.GINKGO_FOCUS_EXIT_CODE) - res.HasProgrammaticFocus = (exitStatus == types.GINKGO_FOCUS_EXIT_CODE) - - return res -} - -func (t *TestRunner) combineCoverprofiles() { - profiles := []string{} - for cpu := 1; cpu <= t.numCPU; cpu++ { - coverFile := fmt.Sprintf("%s.coverprofile.%d", t.Suite.PackageName, cpu) - coverFile = filepath.Join(t.Suite.Path, coverFile) - coverProfile, err := ioutil.ReadFile(coverFile) - os.Remove(coverFile) - - if err == nil { - profiles = append(profiles, string(coverProfile)) - } - } - - if len(profiles) != t.numCPU { - return - } - - lines := map[string]int{} - lineOrder := []string{} - for i, coverProfile := range profiles { - for _, line := range strings.Split(string(coverProfile), "\n")[1:] { - if len(line) == 0 { - continue - } - components := strings.Split(line, " ") - count, _ := strconv.Atoi(components[len(components)-1]) - prefix := strings.Join(components[0:len(components)-1], " ") - lines[prefix] += count - if i == 0 { - lineOrder = append(lineOrder, prefix) - } - } - } - - output := []string{"mode: atomic"} - for _, line := range lineOrder { - output = append(output, fmt.Sprintf("%s %d", line, lines[line])) - } - finalOutput := strings.Join(output, "\n") - ioutil.WriteFile(filepath.Join(t.Suite.Path, fmt.Sprintf("%s.coverprofile", t.Suite.PackageName)), []byte(finalOutput), 0666) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/test_suite.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/test_suite.go deleted file mode 100644 index cc7d2f4..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/test_suite.go +++ /dev/null @@ -1,106 +0,0 @@ -package testsuite - -import ( - "errors" - "io/ioutil" - "os" - "path/filepath" - "regexp" - "strings" -) - -type TestSuite struct { - Path string - PackageName string - IsGinkgo bool - Precompiled bool -} - -func PrecompiledTestSuite(path string) (TestSuite, error) { - info, err := os.Stat(path) - if err != nil { - return TestSuite{}, err - } - - if info.IsDir() { - return TestSuite{}, errors.New("this is a directory, not a file") - } - - if filepath.Ext(path) != ".test" { - return TestSuite{}, errors.New("this is not a .test binary") - } - - if info.Mode()&0111 == 0 { - return TestSuite{}, errors.New("this is not executable") - } - - dir := relPath(filepath.Dir(path)) - packageName := strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) - - return TestSuite{ - Path: dir, - PackageName: packageName, - IsGinkgo: true, - Precompiled: true, - }, nil -} - -func SuitesInDir(dir string, recurse bool) []TestSuite { - suites := []TestSuite{} - files, _ := ioutil.ReadDir(dir) - re := regexp.MustCompile(`_test\.go$`) - for _, file := range files { - if !file.IsDir() && re.Match([]byte(file.Name())) { - suites = append(suites, New(dir, files)) - break - } - } - - if recurse { - re = regexp.MustCompile(`^[._]`) - for _, file := range files { - if file.IsDir() && !re.Match([]byte(file.Name())) { - suites = append(suites, SuitesInDir(dir+"/"+file.Name(), recurse)...) - } - } - } - - return suites -} - -func relPath(dir string) string { - dir, _ = filepath.Abs(dir) - cwd, _ := os.Getwd() - dir, _ = filepath.Rel(cwd, filepath.Clean(dir)) - dir = "." + string(filepath.Separator) + dir - return dir -} - -func New(dir string, files []os.FileInfo) TestSuite { - return TestSuite{ - Path: relPath(dir), - PackageName: packageNameForSuite(dir), - IsGinkgo: filesHaveGinkgoSuite(dir, files), - } -} - -func packageNameForSuite(dir string) string { - path, _ := filepath.Abs(dir) - return filepath.Base(path) -} - -func filesHaveGinkgoSuite(dir string, files []os.FileInfo) bool { - reTestFile := regexp.MustCompile(`_test\.go$`) - reGinkgo := regexp.MustCompile(`package ginkgo|\/ginkgo"`) - - for _, file := range files { - if !file.IsDir() && reTestFile.Match([]byte(file.Name())) { - contents, _ := ioutil.ReadFile(dir + "/" + file.Name()) - if reGinkgo.Match(contents) { - return true - } - } - } - - return false -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_suite_test.go deleted file mode 100644 index d1e8b21..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package testsuite_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestTestsuite(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Testsuite Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_test.go deleted file mode 100644 index 8681ffc..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_test.go +++ /dev/null @@ -1,167 +0,0 @@ -package testsuite_test - -import ( - "io/ioutil" - "os" - "path/filepath" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/ginkgo/testsuite" - . "github.com/onsi/gomega" -) - -var _ = Describe("TestSuite", func() { - var tmpDir string - var relTmpDir string - - writeFile := func(folder string, filename string, content string, mode os.FileMode) { - path := filepath.Join(tmpDir, folder) - err := os.MkdirAll(path, 0700) - Ω(err).ShouldNot(HaveOccurred()) - - path = filepath.Join(path, filename) - ioutil.WriteFile(path, []byte(content), mode) - } - - BeforeEach(func() { - var err error - tmpDir, err = ioutil.TempDir("/tmp", "ginkgo") - Ω(err).ShouldNot(HaveOccurred()) - - cwd, err := os.Getwd() - Ω(err).ShouldNot(HaveOccurred()) - relTmpDir, err = filepath.Rel(cwd, tmpDir) - relTmpDir = "./" + relTmpDir - Ω(err).ShouldNot(HaveOccurred()) - - //go files in the root directory (no tests) - writeFile("/", "main.go", "package main", 0666) - - //non-go files in a nested directory - writeFile("/redherring", "big_test.jpg", "package ginkgo", 0666) - - //non-ginkgo tests in a nested directory - writeFile("/professorplum", "professorplum_test.go", `import "testing"`, 0666) - - //ginkgo tests in a nested directory - writeFile("/colonelmustard", "colonelmustard_test.go", `import "github.com/onsi/ginkgo"`, 0666) - - //ginkgo tests in a deeply nested directory - writeFile("/colonelmustard/library", "library_test.go", `import "github.com/onsi/ginkgo"`, 0666) - - //a precompiled ginkgo test - writeFile("/precompiled-dir", "precompiled.test", `fake-binary-file`, 0777) - writeFile("/precompiled-dir", "some-other-binary", `fake-binary-file`, 0777) - writeFile("/precompiled-dir", "nonexecutable.test", `fake-binary-file`, 0666) - }) - - AfterEach(func() { - os.RemoveAll(tmpDir) - }) - - Describe("Finding precompiled test suites", func() { - Context("if pointed at an executable file that ends with .test", func() { - It("should return a precompiled test suite", func() { - suite, err := PrecompiledTestSuite(filepath.Join(tmpDir, "precompiled-dir", "precompiled.test")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(suite).Should(Equal(TestSuite{ - Path: relTmpDir + "/precompiled-dir", - PackageName: "precompiled", - IsGinkgo: true, - Precompiled: true, - })) - }) - }) - - Context("if pointed at a directory", func() { - It("should error", func() { - suite, err := PrecompiledTestSuite(filepath.Join(tmpDir, "precompiled-dir")) - Ω(suite).Should(BeZero()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("if pointed at an executable that doesn't have .test", func() { - It("should error", func() { - suite, err := PrecompiledTestSuite(filepath.Join(tmpDir, "precompiled-dir", "some-other-binary")) - Ω(suite).Should(BeZero()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("if pointed at a .test that isn't executable", func() { - It("should error", func() { - suite, err := PrecompiledTestSuite(filepath.Join(tmpDir, "precompiled-dir", "nonexecutable.test")) - Ω(suite).Should(BeZero()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("if pointed at a nonexisting file", func() { - It("should error", func() { - suite, err := PrecompiledTestSuite(filepath.Join(tmpDir, "precompiled-dir", "nope-nothing-to-see-here")) - Ω(suite).Should(BeZero()) - Ω(err).Should(HaveOccurred()) - }) - }) - }) - - Describe("scanning for suites in a directory", func() { - Context("when there are no tests in the specified directory", func() { - It("should come up empty", func() { - suites := SuitesInDir(tmpDir, false) - Ω(suites).Should(BeEmpty()) - }) - }) - - Context("when there are ginkgo tests in the specified directory", func() { - It("should return an appropriately configured suite", func() { - suites := SuitesInDir(filepath.Join(tmpDir, "colonelmustard"), false) - Ω(suites).Should(HaveLen(1)) - - Ω(suites[0].Path).Should(Equal(relTmpDir + "/colonelmustard")) - Ω(suites[0].PackageName).Should(Equal("colonelmustard")) - Ω(suites[0].IsGinkgo).Should(BeTrue()) - Ω(suites[0].Precompiled).Should(BeFalse()) - }) - }) - - Context("when there are non-ginkgo tests in the specified directory", func() { - It("should return an appropriately configured suite", func() { - suites := SuitesInDir(filepath.Join(tmpDir, "professorplum"), false) - Ω(suites).Should(HaveLen(1)) - - Ω(suites[0].Path).Should(Equal(relTmpDir + "/professorplum")) - Ω(suites[0].PackageName).Should(Equal("professorplum")) - Ω(suites[0].IsGinkgo).Should(BeFalse()) - Ω(suites[0].Precompiled).Should(BeFalse()) - }) - }) - - Context("when recursively scanning", func() { - It("should return suites for corresponding test suites, only", func() { - suites := SuitesInDir(tmpDir, true) - Ω(suites).Should(HaveLen(3)) - - Ω(suites).Should(ContainElement(TestSuite{ - Path: relTmpDir + "/colonelmustard", - PackageName: "colonelmustard", - IsGinkgo: true, - Precompiled: false, - })) - Ω(suites).Should(ContainElement(TestSuite{ - Path: relTmpDir + "/professorplum", - PackageName: "professorplum", - IsGinkgo: false, - Precompiled: false, - })) - Ω(suites).Should(ContainElement(TestSuite{ - Path: relTmpDir + "/colonelmustard/library", - PackageName: "library", - IsGinkgo: true, - Precompiled: false, - })) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/unfocus_command.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/unfocus_command.go deleted file mode 100644 index 16f3c3b..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/unfocus_command.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "os/exec" -) - -func BuildUnfocusCommand() *Command { - return &Command{ - Name: "unfocus", - AltName: "blur", - FlagSet: flag.NewFlagSet("unfocus", flag.ExitOnError), - UsageCommand: "ginkgo unfocus (or ginkgo blur)", - Usage: []string{ - "Recursively unfocuses any focused tests under the current directory", - }, - Command: unfocusSpecs, - } -} - -func unfocusSpecs([]string, []string) { - unfocus("Describe") - unfocus("Context") - unfocus("It") - unfocus("Measure") -} - -func unfocus(component string) { - fmt.Printf("Removing F%s...\n", component) - cmd := exec.Command("gofmt", fmt.Sprintf("-r=F%s -> %s", component, component), "-w", ".") - out, _ := cmd.CombinedOutput() - if string(out) != "" { - println(string(out)) - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/version_command.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/version_command.go deleted file mode 100644 index cdca3a3..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/version_command.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "github.com/onsi/ginkgo/config" -) - -func BuildVersionCommand() *Command { - return &Command{ - Name: "version", - FlagSet: flag.NewFlagSet("version", flag.ExitOnError), - UsageCommand: "ginkgo version", - Usage: []string{ - "Print Ginkgo's version", - }, - Command: printVersion, - } -} - -func printVersion([]string, []string) { - fmt.Printf("Ginkgo Version %s\n", config.VERSION) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/delta.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/delta.go deleted file mode 100644 index 6c485c5..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/delta.go +++ /dev/null @@ -1,22 +0,0 @@ -package watch - -import "sort" - -type Delta struct { - ModifiedPackages []string - - NewSuites []*Suite - RemovedSuites []*Suite - modifiedSuites []*Suite -} - -type DescendingByDelta []*Suite - -func (a DescendingByDelta) Len() int { return len(a) } -func (a DescendingByDelta) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a DescendingByDelta) Less(i, j int) bool { return a[i].Delta() > a[j].Delta() } - -func (d Delta) ModifiedSuites() []*Suite { - sort.Sort(DescendingByDelta(d.modifiedSuites)) - return d.modifiedSuites -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/delta_tracker.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/delta_tracker.go deleted file mode 100644 index 452c07e..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/delta_tracker.go +++ /dev/null @@ -1,71 +0,0 @@ -package watch - -import ( - "fmt" - - "github.com/onsi/ginkgo/ginkgo/testsuite" -) - -type SuiteErrors map[testsuite.TestSuite]error - -type DeltaTracker struct { - maxDepth int - suites map[string]*Suite - packageHashes *PackageHashes -} - -func NewDeltaTracker(maxDepth int) *DeltaTracker { - return &DeltaTracker{ - maxDepth: maxDepth, - packageHashes: NewPackageHashes(), - suites: map[string]*Suite{}, - } -} - -func (d *DeltaTracker) Delta(suites []testsuite.TestSuite) (delta Delta, errors SuiteErrors) { - errors = SuiteErrors{} - delta.ModifiedPackages = d.packageHashes.CheckForChanges() - - providedSuitePaths := map[string]bool{} - for _, suite := range suites { - providedSuitePaths[suite.Path] = true - } - - d.packageHashes.StartTrackingUsage() - - for _, suite := range d.suites { - if providedSuitePaths[suite.Suite.Path] { - if suite.Delta() > 0 { - delta.modifiedSuites = append(delta.modifiedSuites, suite) - } - } else { - delta.RemovedSuites = append(delta.RemovedSuites, suite) - } - } - - d.packageHashes.StopTrackingUsageAndPrune() - - for _, suite := range suites { - _, ok := d.suites[suite.Path] - if !ok { - s, err := NewSuite(suite, d.maxDepth, d.packageHashes) - if err != nil { - errors[suite] = err - continue - } - d.suites[suite.Path] = s - delta.NewSuites = append(delta.NewSuites, s) - } - } - - return delta, errors -} - -func (d *DeltaTracker) WillRun(suite testsuite.TestSuite) error { - s, ok := d.suites[suite.Path] - if !ok { - return fmt.Errorf("unknown suite %s", suite.Path) - } - - return s.MarkAsRunAndRecomputedDependencies(d.maxDepth) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/dependencies.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/dependencies.go deleted file mode 100644 index 82c25fa..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/dependencies.go +++ /dev/null @@ -1,91 +0,0 @@ -package watch - -import ( - "go/build" - "regexp" -) - -var ginkgoAndGomegaFilter = regexp.MustCompile(`github\.com/onsi/ginkgo|github\.com/onsi/gomega`) - -type Dependencies struct { - deps map[string]int -} - -func NewDependencies(path string, maxDepth int) (Dependencies, error) { - d := Dependencies{ - deps: map[string]int{}, - } - - if maxDepth == 0 { - return d, nil - } - - err := d.seedWithDepsForPackageAtPath(path) - if err != nil { - return d, err - } - - for depth := 1; depth < maxDepth; depth++ { - n := len(d.deps) - d.addDepsForDepth(depth) - if n == len(d.deps) { - break - } - } - - return d, nil -} - -func (d Dependencies) Dependencies() map[string]int { - return d.deps -} - -func (d Dependencies) seedWithDepsForPackageAtPath(path string) error { - pkg, err := build.ImportDir(path, 0) - if err != nil { - return err - } - - d.resolveAndAdd(pkg.Imports, 1) - d.resolveAndAdd(pkg.TestImports, 1) - d.resolveAndAdd(pkg.XTestImports, 1) - - delete(d.deps, pkg.Dir) - return nil -} - -func (d Dependencies) addDepsForDepth(depth int) { - for dep, depDepth := range d.deps { - if depDepth == depth { - d.addDepsForDep(dep, depth+1) - } - } -} - -func (d Dependencies) addDepsForDep(dep string, depth int) { - pkg, err := build.ImportDir(dep, 0) - if err != nil { - println(err.Error()) - return - } - d.resolveAndAdd(pkg.Imports, depth) -} - -func (d Dependencies) resolveAndAdd(deps []string, depth int) { - for _, dep := range deps { - pkg, err := build.Import(dep, ".", 0) - if err != nil { - continue - } - if pkg.Goroot == false && !ginkgoAndGomegaFilter.Match([]byte(pkg.Dir)) { - d.addDepIfNotPresent(pkg.Dir, depth) - } - } -} - -func (d Dependencies) addDepIfNotPresent(dep string, depth int) { - _, ok := d.deps[dep] - if !ok { - d.deps[dep] = depth - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/package_hash.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/package_hash.go deleted file mode 100644 index eaf357c..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/package_hash.go +++ /dev/null @@ -1,103 +0,0 @@ -package watch - -import ( - "fmt" - "io/ioutil" - "os" - "regexp" - "time" -) - -var goRegExp = regexp.MustCompile(`\.go$`) -var goTestRegExp = regexp.MustCompile(`_test\.go$`) - -type PackageHash struct { - CodeModifiedTime time.Time - TestModifiedTime time.Time - Deleted bool - - path string - codeHash string - testHash string -} - -func NewPackageHash(path string) *PackageHash { - p := &PackageHash{ - path: path, - } - - p.codeHash, _, p.testHash, _, p.Deleted = p.computeHashes() - - return p -} - -func (p *PackageHash) CheckForChanges() bool { - codeHash, codeModifiedTime, testHash, testModifiedTime, deleted := p.computeHashes() - - if deleted { - if p.Deleted == false { - t := time.Now() - p.CodeModifiedTime = t - p.TestModifiedTime = t - } - p.Deleted = true - return true - } - - modified := false - p.Deleted = false - - if p.codeHash != codeHash { - p.CodeModifiedTime = codeModifiedTime - modified = true - } - if p.testHash != testHash { - p.TestModifiedTime = testModifiedTime - modified = true - } - - p.codeHash = codeHash - p.testHash = testHash - return modified -} - -func (p *PackageHash) computeHashes() (codeHash string, codeModifiedTime time.Time, testHash string, testModifiedTime time.Time, deleted bool) { - infos, err := ioutil.ReadDir(p.path) - - if err != nil { - deleted = true - return - } - - for _, info := range infos { - if info.IsDir() { - continue - } - - if goTestRegExp.Match([]byte(info.Name())) { - testHash += p.hashForFileInfo(info) - if info.ModTime().After(testModifiedTime) { - testModifiedTime = info.ModTime() - } - continue - } - - if goRegExp.Match([]byte(info.Name())) { - codeHash += p.hashForFileInfo(info) - if info.ModTime().After(codeModifiedTime) { - codeModifiedTime = info.ModTime() - } - } - } - - testHash += codeHash - if codeModifiedTime.After(testModifiedTime) { - testModifiedTime = codeModifiedTime - } - - return -} - -func (p *PackageHash) hashForFileInfo(info os.FileInfo) string { - return fmt.Sprintf("%s_%d_%d", info.Name(), info.Size(), info.ModTime().UnixNano()) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/package_hashes.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/package_hashes.go deleted file mode 100644 index 262eaa8..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/package_hashes.go +++ /dev/null @@ -1,82 +0,0 @@ -package watch - -import ( - "path/filepath" - "sync" -) - -type PackageHashes struct { - PackageHashes map[string]*PackageHash - usedPaths map[string]bool - lock *sync.Mutex -} - -func NewPackageHashes() *PackageHashes { - return &PackageHashes{ - PackageHashes: map[string]*PackageHash{}, - usedPaths: nil, - lock: &sync.Mutex{}, - } -} - -func (p *PackageHashes) CheckForChanges() []string { - p.lock.Lock() - defer p.lock.Unlock() - - modified := []string{} - - for _, packageHash := range p.PackageHashes { - if packageHash.CheckForChanges() { - modified = append(modified, packageHash.path) - } - } - - return modified -} - -func (p *PackageHashes) Add(path string) *PackageHash { - p.lock.Lock() - defer p.lock.Unlock() - - path, _ = filepath.Abs(path) - _, ok := p.PackageHashes[path] - if !ok { - p.PackageHashes[path] = NewPackageHash(path) - } - - if p.usedPaths != nil { - p.usedPaths[path] = true - } - return p.PackageHashes[path] -} - -func (p *PackageHashes) Get(path string) *PackageHash { - p.lock.Lock() - defer p.lock.Unlock() - - path, _ = filepath.Abs(path) - if p.usedPaths != nil { - p.usedPaths[path] = true - } - return p.PackageHashes[path] -} - -func (p *PackageHashes) StartTrackingUsage() { - p.lock.Lock() - defer p.lock.Unlock() - - p.usedPaths = map[string]bool{} -} - -func (p *PackageHashes) StopTrackingUsageAndPrune() { - p.lock.Lock() - defer p.lock.Unlock() - - for path := range p.PackageHashes { - if !p.usedPaths[path] { - delete(p.PackageHashes, path) - } - } - - p.usedPaths = nil -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/suite.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/suite.go deleted file mode 100644 index 5deaba7..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch/suite.go +++ /dev/null @@ -1,87 +0,0 @@ -package watch - -import ( - "fmt" - "math" - "time" - - "github.com/onsi/ginkgo/ginkgo/testsuite" -) - -type Suite struct { - Suite testsuite.TestSuite - RunTime time.Time - Dependencies Dependencies - - sharedPackageHashes *PackageHashes -} - -func NewSuite(suite testsuite.TestSuite, maxDepth int, sharedPackageHashes *PackageHashes) (*Suite, error) { - deps, err := NewDependencies(suite.Path, maxDepth) - if err != nil { - return nil, err - } - - sharedPackageHashes.Add(suite.Path) - for dep := range deps.Dependencies() { - sharedPackageHashes.Add(dep) - } - - return &Suite{ - Suite: suite, - Dependencies: deps, - - sharedPackageHashes: sharedPackageHashes, - }, nil -} - -func (s *Suite) Delta() float64 { - delta := s.delta(s.Suite.Path, true, 0) * 1000 - for dep, depth := range s.Dependencies.Dependencies() { - delta += s.delta(dep, false, depth) - } - return delta -} - -func (s *Suite) MarkAsRunAndRecomputedDependencies(maxDepth int) error { - s.RunTime = time.Now() - - deps, err := NewDependencies(s.Suite.Path, maxDepth) - if err != nil { - return err - } - - s.sharedPackageHashes.Add(s.Suite.Path) - for dep := range deps.Dependencies() { - s.sharedPackageHashes.Add(dep) - } - - s.Dependencies = deps - - return nil -} - -func (s *Suite) Description() string { - numDeps := len(s.Dependencies.Dependencies()) - pluralizer := "ies" - if numDeps == 1 { - pluralizer = "y" - } - return fmt.Sprintf("%s [%d dependenc%s]", s.Suite.Path, numDeps, pluralizer) -} - -func (s *Suite) delta(packagePath string, includeTests bool, depth int) float64 { - return math.Max(float64(s.dt(packagePath, includeTests)), 0) / float64(depth+1) -} - -func (s *Suite) dt(packagePath string, includeTests bool) time.Duration { - packageHash := s.sharedPackageHashes.Get(packagePath) - var modifiedTime time.Time - if includeTests { - modifiedTime = packageHash.TestModifiedTime - } else { - modifiedTime = packageHash.CodeModifiedTime - } - - return modifiedTime.Sub(s.RunTime) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch_command.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch_command.go deleted file mode 100644 index 9736122..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/watch_command.go +++ /dev/null @@ -1,172 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/ginkgo/interrupthandler" - "github.com/onsi/ginkgo/ginkgo/testrunner" - "github.com/onsi/ginkgo/ginkgo/testsuite" - "github.com/onsi/ginkgo/ginkgo/watch" -) - -func BuildWatchCommand() *Command { - commandFlags := NewWatchCommandFlags(flag.NewFlagSet("watch", flag.ExitOnError)) - interruptHandler := interrupthandler.NewInterruptHandler() - notifier := NewNotifier(commandFlags) - watcher := &SpecWatcher{ - commandFlags: commandFlags, - notifier: notifier, - interruptHandler: interruptHandler, - suiteRunner: NewSuiteRunner(notifier, interruptHandler), - } - - return &Command{ - Name: "watch", - FlagSet: commandFlags.FlagSet, - UsageCommand: "ginkgo watch -- ", - Usage: []string{ - "Watches the tests in the passed in and runs them when changes occur.", - "Any arguments after -- will be passed to the test.", - }, - Command: watcher.WatchSpecs, - SuppressFlagDocumentation: true, - FlagDocSubstitute: []string{ - "Accepts all the flags that the ginkgo command accepts except for --keepGoing and --untilItFails", - }, - } -} - -type SpecWatcher struct { - commandFlags *RunWatchAndBuildCommandFlags - notifier *Notifier - interruptHandler *interrupthandler.InterruptHandler - suiteRunner *SuiteRunner -} - -func (w *SpecWatcher) WatchSpecs(args []string, additionalArgs []string) { - w.commandFlags.computeNodes() - w.notifier.VerifyNotificationsAreAvailable() - - w.WatchSuites(args, additionalArgs) -} - -func (w *SpecWatcher) runnersForSuites(suites []testsuite.TestSuite, additionalArgs []string) []*testrunner.TestRunner { - runners := []*testrunner.TestRunner{} - - for _, suite := range suites { - runners = append(runners, testrunner.New(suite, w.commandFlags.NumCPU, w.commandFlags.ParallelStream, w.commandFlags.Race, w.commandFlags.Cover, w.commandFlags.CoverPkg, w.commandFlags.Tags, additionalArgs)) - } - - return runners -} - -func (w *SpecWatcher) WatchSuites(args []string, additionalArgs []string) { - suites, _ := findSuites(args, w.commandFlags.Recurse, w.commandFlags.SkipPackage, false) - - if len(suites) == 0 { - complainAndQuit("Found no test suites") - } - - fmt.Printf("Identified %d test %s. Locating dependencies to a depth of %d (this may take a while)...\n", len(suites), pluralizedWord("suite", "suites", len(suites)), w.commandFlags.Depth) - deltaTracker := watch.NewDeltaTracker(w.commandFlags.Depth) - delta, errors := deltaTracker.Delta(suites) - - fmt.Printf("Watching %d %s:\n", len(delta.NewSuites), pluralizedWord("suite", "suites", len(delta.NewSuites))) - for _, suite := range delta.NewSuites { - fmt.Println(" " + suite.Description()) - } - - for suite, err := range errors { - fmt.Printf("Failed to watch %s: %s\n"+suite.PackageName, err) - } - - if len(suites) == 1 { - runners := w.runnersForSuites(suites, additionalArgs) - w.suiteRunner.RunSuites(runners, w.commandFlags.NumCompilers, true, nil) - runners[0].CleanUp() - } - - ticker := time.NewTicker(time.Second) - - for { - select { - case <-ticker.C: - suites, _ := findSuites(args, w.commandFlags.Recurse, w.commandFlags.SkipPackage, false) - delta, _ := deltaTracker.Delta(suites) - - suitesToRun := []testsuite.TestSuite{} - - if len(delta.NewSuites) > 0 { - fmt.Printf(greenColor+"Detected %d new %s:\n"+defaultStyle, len(delta.NewSuites), pluralizedWord("suite", "suites", len(delta.NewSuites))) - for _, suite := range delta.NewSuites { - suitesToRun = append(suitesToRun, suite.Suite) - fmt.Println(" " + suite.Description()) - } - } - - modifiedSuites := delta.ModifiedSuites() - if len(modifiedSuites) > 0 { - fmt.Println(greenColor + "\nDetected changes in:" + defaultStyle) - for _, pkg := range delta.ModifiedPackages { - fmt.Println(" " + pkg) - } - fmt.Printf(greenColor+"Will run %d %s:\n"+defaultStyle, len(modifiedSuites), pluralizedWord("suite", "suites", len(modifiedSuites))) - for _, suite := range modifiedSuites { - suitesToRun = append(suitesToRun, suite.Suite) - fmt.Println(" " + suite.Description()) - } - fmt.Println("") - } - - if len(suitesToRun) > 0 { - w.UpdateSeed() - w.ComputeSuccinctMode(len(suitesToRun)) - runners := w.runnersForSuites(suitesToRun, additionalArgs) - result, _ := w.suiteRunner.RunSuites(runners, w.commandFlags.NumCompilers, true, func(suite testsuite.TestSuite) { - deltaTracker.WillRun(suite) - }) - for _, runner := range runners { - runner.CleanUp() - } - if !w.interruptHandler.WasInterrupted() { - color := redColor - if result.Passed { - color = greenColor - } - fmt.Println(color + "\nDone. Resuming watch..." + defaultStyle) - } - } - - case <-w.interruptHandler.C: - return - } - } -} - -func (w *SpecWatcher) ComputeSuccinctMode(numSuites int) { - if config.DefaultReporterConfig.Verbose { - config.DefaultReporterConfig.Succinct = false - return - } - - if w.commandFlags.wasSet("succinct") { - return - } - - if numSuites == 1 { - config.DefaultReporterConfig.Succinct = false - } - - if numSuites > 1 { - config.DefaultReporterConfig.Succinct = true - } -} - -func (w *SpecWatcher) UpdateSeed() { - if !w.commandFlags.wasSet("seed") { - config.GinkgoConfig.RandomSeed = time.Now().Unix() - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo_dsl.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo_dsl.go deleted file mode 100644 index 0323684..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo_dsl.go +++ /dev/null @@ -1,525 +0,0 @@ -/* -Ginkgo is a BDD-style testing framework for Golang - -The godoc documentation describes Ginkgo's API. More comprehensive documentation (with examples!) is available at http://onsi.github.io/ginkgo/ - -Ginkgo's preferred matcher library is [Gomega](http://github.com/onsi/gomega) - -Ginkgo on Github: http://github.com/onsi/ginkgo - -Ginkgo is MIT-Licensed -*/ -package ginkgo - -import ( - "flag" - "fmt" - "io" - "net/http" - "os" - "strings" - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/remote" - "github.com/onsi/ginkgo/internal/suite" - "github.com/onsi/ginkgo/internal/testingtproxy" - "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" -) - -const GINKGO_VERSION = config.VERSION -const GINKGO_PANIC = ` -Your test failed. -Ginkgo panics to prevent subsequent assertions from running. -Normally Ginkgo rescues this panic so you shouldn't see it. - -But, if you make an assertion in a goroutine, Ginkgo can't capture the panic. -To circumvent this, you should call - - defer GinkgoRecover() - -at the top of the goroutine that caused this panic. -` -const defaultTimeout = 1 - -var globalSuite *suite.Suite -var globalFailer *failer.Failer - -func init() { - config.Flags(flag.CommandLine, "ginkgo", true) - GinkgoWriter = writer.New(os.Stdout) - globalFailer = failer.New() - globalSuite = suite.New(globalFailer) -} - -//GinkgoWriter implements an io.Writer -//When running in verbose mode any writes to GinkgoWriter will be immediately printed -//to stdout. Otherwise, GinkgoWriter will buffer any writes produced during the current test and flush them to screen -//only if the current test fails. -var GinkgoWriter io.Writer - -//The interface by which Ginkgo receives *testing.T -type GinkgoTestingT interface { - Fail() -} - -//GinkgoParallelNode returns the parallel node number for the current ginkgo process -//The node number is 1-indexed -func GinkgoParallelNode() int { - return config.GinkgoConfig.ParallelNode -} - -//Some matcher libraries or legacy codebases require a *testing.T -//GinkgoT implements an interface analogous to *testing.T and can be used if -//the library in question accepts *testing.T through an interface -// -// For example, with testify: -// assert.Equal(GinkgoT(), 123, 123, "they should be equal") -// -// Or with gomock: -// gomock.NewController(GinkgoT()) -// -// GinkgoT() takes an optional offset argument that can be used to get the -// correct line number associated with the failure. -func GinkgoT(optionalOffset ...int) GinkgoTInterface { - offset := 3 - if len(optionalOffset) > 0 { - offset = optionalOffset[0] - } - return testingtproxy.New(GinkgoWriter, Fail, offset) -} - -//The interface returned by GinkgoT(). This covers most of the methods -//in the testing package's T. -type GinkgoTInterface interface { - Fail() - Error(args ...interface{}) - Errorf(format string, args ...interface{}) - FailNow() - Fatal(args ...interface{}) - Fatalf(format string, args ...interface{}) - Log(args ...interface{}) - Logf(format string, args ...interface{}) - Failed() bool - Parallel() - Skip(args ...interface{}) - Skipf(format string, args ...interface{}) - SkipNow() - Skipped() bool -} - -//Custom Ginkgo test reporters must implement the Reporter interface. -// -//The custom reporter is passed in a SuiteSummary when the suite begins and ends, -//and a SpecSummary just before a spec begins and just after a spec ends -type Reporter reporters.Reporter - -//Asynchronous specs are given a channel of the Done type. You must close or write to the channel -//to tell Ginkgo that your async test is done. -type Done chan<- interface{} - -//GinkgoTestDescription represents the information about the current running test returned by CurrentGinkgoTestDescription -// FullTestText: a concatenation of ComponentTexts and the TestText -// ComponentTexts: a list of all texts for the Describes & Contexts leading up to the current test -// TestText: the text in the actual It or Measure node -// IsMeasurement: true if the current test is a measurement -// FileName: the name of the file containing the current test -// LineNumber: the line number for the current test -// Failed: if the current test has failed, this will be true (useful in an AfterEach) -type GinkgoTestDescription struct { - FullTestText string - ComponentTexts []string - TestText string - - IsMeasurement bool - - FileName string - LineNumber int - - Failed bool -} - -//CurrentGinkgoTestDescripton returns information about the current running test. -func CurrentGinkgoTestDescription() GinkgoTestDescription { - summary, ok := globalSuite.CurrentRunningSpecSummary() - if !ok { - return GinkgoTestDescription{} - } - - subjectCodeLocation := summary.ComponentCodeLocations[len(summary.ComponentCodeLocations)-1] - - return GinkgoTestDescription{ - ComponentTexts: summary.ComponentTexts[1:], - FullTestText: strings.Join(summary.ComponentTexts[1:], " "), - TestText: summary.ComponentTexts[len(summary.ComponentTexts)-1], - IsMeasurement: summary.IsMeasurement, - FileName: subjectCodeLocation.FileName, - LineNumber: subjectCodeLocation.LineNumber, - Failed: summary.HasFailureState(), - } -} - -//Measurement tests receive a Benchmarker. -// -//You use the Time() function to time how long the passed in body function takes to run -//You use the RecordValue() function to track arbitrary numerical measurements. -//The optional info argument is passed to the test reporter and can be used to -// provide the measurement data to a custom reporter with context. -// -//See http://onsi.github.io/ginkgo/#benchmark_tests for more details -type Benchmarker interface { - Time(name string, body func(), info ...interface{}) (elapsedTime time.Duration) - RecordValue(name string, value float64, info ...interface{}) -} - -//RunSpecs is the entry point for the Ginkgo test runner. -//You must call this within a Golang testing TestX(t *testing.T) function. -// -//To bootstrap a test suite you can use the Ginkgo CLI: -// -// ginkgo bootstrap -func RunSpecs(t GinkgoTestingT, description string) bool { - specReporters := []Reporter{buildDefaultReporter()} - return RunSpecsWithCustomReporters(t, description, specReporters) -} - -//To run your tests with Ginkgo's default reporter and your custom reporter(s), replace -//RunSpecs() with this method. -func RunSpecsWithDefaultAndCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool { - specReporters = append([]Reporter{buildDefaultReporter()}, specReporters...) - return RunSpecsWithCustomReporters(t, description, specReporters) -} - -//To run your tests with your custom reporter(s) (and *not* Ginkgo's default reporter), replace -//RunSpecs() with this method. Note that parallel tests will not work correctly without the default reporter -func RunSpecsWithCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool { - writer := GinkgoWriter.(*writer.Writer) - writer.SetStream(config.DefaultReporterConfig.Verbose) - reporters := make([]reporters.Reporter, len(specReporters)) - for i, reporter := range specReporters { - reporters[i] = reporter - } - passed, hasFocusedTests := globalSuite.Run(t, description, reporters, writer, config.GinkgoConfig) - if passed && hasFocusedTests { - fmt.Println("PASS | FOCUSED") - os.Exit(types.GINKGO_FOCUS_EXIT_CODE) - } - return passed -} - -func buildDefaultReporter() Reporter { - remoteReportingServer := config.GinkgoConfig.StreamHost - if remoteReportingServer == "" { - stenographer := stenographer.New(!config.DefaultReporterConfig.NoColor) - return reporters.NewDefaultReporter(config.DefaultReporterConfig, stenographer) - } else { - return remote.NewForwardingReporter(remoteReportingServer, &http.Client{}, remote.NewOutputInterceptor()) - } -} - -//Fail notifies Ginkgo that the current spec has failed. (Gomega will call Fail for you automatically when an assertion fails.) -func Fail(message string, callerSkip ...int) { - skip := 0 - if len(callerSkip) > 0 { - skip = callerSkip[0] - } - - globalFailer.Fail(message, codelocation.New(skip+1)) - panic(GINKGO_PANIC) -} - -//GinkgoRecover should be deferred at the top of any spawned goroutine that (may) call `Fail` -//Since Gomega assertions call fail, you should throw a `defer GinkgoRecover()` at the top of any goroutine that -//calls out to Gomega -// -//Here's why: Ginkgo's `Fail` method records the failure and then panics to prevent -//further assertions from running. This panic must be recovered. Ginkgo does this for you -//if the panic originates in a Ginkgo node (an It, BeforeEach, etc...) -// -//Unfortunately, if a panic originates on a goroutine *launched* from one of these nodes there's no -//way for Ginkgo to rescue the panic. To do this, you must remember to `defer GinkgoRecover()` at the top of such a goroutine. -func GinkgoRecover() { - e := recover() - if e != nil { - globalFailer.Panic(codelocation.New(1), e) - } -} - -//Describe blocks allow you to organize your specs. A Describe block can contain any number of -//BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks. -// -//In addition you can nest Describe and Context blocks. Describe and Context blocks are functionally -//equivalent. The difference is purely semantic -- you typical Describe the behavior of an object -//or method and, within that Describe, outline a number of Contexts. -func Describe(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1)) - return true -} - -//You can focus the tests within a describe block using FDescribe -func FDescribe(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using PDescribe -func PDescribe(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using XDescribe -func XDescribe(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//Context blocks allow you to organize your specs. A Context block can contain any number of -//BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks. -// -//In addition you can nest Describe and Context blocks. Describe and Context blocks are functionally -//equivalent. The difference is purely semantic -- you typical Describe the behavior of an object -//or method and, within that Describe, outline a number of Contexts. -func Context(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1)) - return true -} - -//You can focus the tests within a describe block using FContext -func FContext(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using PContext -func PContext(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using XContext -func XContext(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//It blocks contain your test code and assertions. You cannot nest any other Ginkgo blocks -//within an It block. -// -//Ginkgo will normally run It blocks synchronously. To perform asynchronous tests, pass a -//function that accepts a Done channel. When you do this, you can also provide an optional timeout. -func It(text string, body interface{}, timeout ...float64) bool { - globalSuite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//You can focus individual Its using FIt -func FIt(text string, body interface{}, timeout ...float64) bool { - globalSuite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//You can mark Its as pending using PIt -func PIt(text string, _ ...interface{}) bool { - globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//You can mark Its as pending using XIt -func XIt(text string, _ ...interface{}) bool { - globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//By allows you to better document large Its. -// -//Generally you should try to keep your Its short and to the point. This is not always possible, however, -//especially in the context of integration tests that capture a particular workflow. -// -//By allows you to document such flows. By must be called within a runnable node (It, BeforeEach, Measure, etc...) -//By will simply log the passed in text to the GinkgoWriter. If By is handed a function it will immediately run the function. -func By(text string, callbacks ...func()) { - preamble := "\x1b[1mSTEP\x1b[0m" - if config.DefaultReporterConfig.NoColor { - preamble = "STEP" - } - fmt.Fprintln(GinkgoWriter, preamble+": "+text) - if len(callbacks) == 1 { - callbacks[0]() - } - if len(callbacks) > 1 { - panic("just one callback per By, please") - } -} - -//Measure blocks run the passed in body function repeatedly (determined by the samples argument) -//and accumulate metrics provided to the Benchmarker by the body function. -// -//The body function must have the signature: -// func(b Benchmarker) -func Measure(text string, body interface{}, samples int) bool { - globalSuite.PushMeasureNode(text, body, types.FlagTypeNone, codelocation.New(1), samples) - return true -} - -//You can focus individual Measures using FMeasure -func FMeasure(text string, body interface{}, samples int) bool { - globalSuite.PushMeasureNode(text, body, types.FlagTypeFocused, codelocation.New(1), samples) - return true -} - -//You can mark Maeasurements as pending using PMeasure -func PMeasure(text string, _ ...interface{}) bool { - globalSuite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//You can mark Maeasurements as pending using XMeasure -func XMeasure(text string, _ ...interface{}) bool { - globalSuite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//BeforeSuite blocks are run just once before any specs are run. When running in parallel, each -//parallel node process will call BeforeSuite. -// -//BeforeSuite blocks can be made asynchronous by providing a body function that accepts a Done channel -// -//You may only register *one* BeforeSuite handler per test suite. You typically do so in your bootstrap file at the top level. -func BeforeSuite(body interface{}, timeout ...float64) bool { - globalSuite.SetBeforeSuiteNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//AfterSuite blocks are *always* run after all the specs regardless of whether specs have passed or failed. -//Moreover, if Ginkgo receives an interrupt signal (^C) it will attempt to run the AfterSuite before exiting. -// -//When running in parallel, each parallel node process will call AfterSuite. -// -//AfterSuite blocks can be made asynchronous by providing a body function that accepts a Done channel -// -//You may only register *one* AfterSuite handler per test suite. You typically do so in your bootstrap file at the top level. -func AfterSuite(body interface{}, timeout ...float64) bool { - globalSuite.SetAfterSuiteNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//SynchronizedBeforeSuite blocks are primarily meant to solve the problem of setting up singleton external resources shared across -//nodes when running tests in parallel. For example, say you have a shared database that you can only start one instance of that -//must be used in your tests. When running in parallel, only one node should set up the database and all other nodes should wait -//until that node is done before running. -// -//SynchronizedBeforeSuite accomplishes this by taking *two* function arguments. The first is only run on parallel node #1. The second is -//run on all nodes, but *only* after the first function completes succesfully. Ginkgo also makes it possible to send data from the first function (on Node 1) -//to the second function (on all the other nodes). -// -//The functions have the following signatures. The first function (which only runs on node 1) has the signature: -// -// func() []byte -// -//or, to run asynchronously: -// -// func(done Done) []byte -// -//The byte array returned by the first function is then passed to the second function, which has the signature: -// -// func(data []byte) -// -//or, to run asynchronously: -// -// func(data []byte, done Done) -// -//Here's a simple pseudo-code example that starts a shared database on Node 1 and shares the database's address with the other nodes: -// -// var dbClient db.Client -// var dbRunner db.Runner -// -// var _ = SynchronizedBeforeSuite(func() []byte { -// dbRunner = db.NewRunner() -// err := dbRunner.Start() -// Ω(err).ShouldNot(HaveOccurred()) -// return []byte(dbRunner.URL) -// }, func(data []byte) { -// dbClient = db.NewClient() -// err := dbClient.Connect(string(data)) -// Ω(err).ShouldNot(HaveOccurred()) -// }) -func SynchronizedBeforeSuite(node1Body interface{}, allNodesBody interface{}, timeout ...float64) bool { - globalSuite.SetSynchronizedBeforeSuiteNode( - node1Body, - allNodesBody, - codelocation.New(1), - parseTimeout(timeout...), - ) - return true -} - -//SynchronizedAfterSuite blocks complement the SynchronizedBeforeSuite blocks in solving the problem of setting up -//external singleton resources shared across nodes when running tests in parallel. -// -//SynchronizedAfterSuite accomplishes this by taking *two* function arguments. The first runs on all nodes. The second runs only on parallel node #1 -//and *only* after all other nodes have finished and exited. This ensures that node 1, and any resources it is running, remain alive until -//all other nodes are finished. -// -//Both functions have the same signature: either func() or func(done Done) to run asynchronously. -// -//Here's a pseudo-code example that complements that given in SynchronizedBeforeSuite. Here, SynchronizedAfterSuite is used to tear down the shared database -//only after all nodes have finished: -// -// var _ = SynchronizedAfterSuite(func() { -// dbClient.Cleanup() -// }, func() { -// dbRunner.Stop() -// }) -func SynchronizedAfterSuite(allNodesBody interface{}, node1Body interface{}, timeout ...float64) bool { - globalSuite.SetSynchronizedAfterSuiteNode( - allNodesBody, - node1Body, - codelocation.New(1), - parseTimeout(timeout...), - ) - return true -} - -//BeforeEach blocks are run before It blocks. When multiple BeforeEach blocks are defined in nested -//Describe and Context blocks the outermost BeforeEach blocks are run first. -// -//Like It blocks, BeforeEach blocks can be made asynchronous by providing a body function that accepts -//a Done channel -func BeforeEach(body interface{}, timeout ...float64) bool { - globalSuite.PushBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//JustBeforeEach blocks are run before It blocks but *after* all BeforeEach blocks. For more details, -//read the [documentation](http://onsi.github.io/ginkgo/#separating_creation_and_configuration_) -// -//Like It blocks, BeforeEach blocks can be made asynchronous by providing a body function that accepts -//a Done channel -func JustBeforeEach(body interface{}, timeout ...float64) bool { - globalSuite.PushJustBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//AfterEach blocks are run after It blocks. When multiple AfterEach blocks are defined in nested -//Describe and Context blocks the innermost AfterEach blocks are run first. -// -//Like It blocks, AfterEach blocks can be made asynchronous by providing a body function that accepts -//a Done channel -func AfterEach(body interface{}, timeout ...float64) bool { - globalSuite.PushAfterEachNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -func parseTimeout(timeout ...float64) time.Duration { - if len(timeout) == 0 { - return time.Duration(defaultTimeout * int64(time.Second)) - } else { - return time.Duration(timeout[0] * float64(time.Second)) - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/convert_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/convert_test.go deleted file mode 100644 index f4fd678..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/convert_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package integration_test - -import ( - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "strings" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ginkgo convert", func() { - var tmpDir string - - readConvertedFileNamed := func(pathComponents ...string) string { - pathToFile := filepath.Join(tmpDir, "convert_fixtures", filepath.Join(pathComponents...)) - bytes, err := ioutil.ReadFile(pathToFile) - ExpectWithOffset(1, err).NotTo(HaveOccurred()) - - return string(bytes) - } - - readGoldMasterNamed := func(filename string) string { - bytes, err := ioutil.ReadFile(filepath.Join("_fixtures", "convert_goldmasters", filename)) - Ω(err).ShouldNot(HaveOccurred()) - - return string(bytes) - } - - BeforeEach(func() { - var err error - - tmpDir, err = ioutil.TempDir("", "ginkgo-convert") - Ω(err).ShouldNot(HaveOccurred()) - - err = exec.Command("cp", "-r", filepath.Join("_fixtures", "convert_fixtures"), tmpDir).Run() - Ω(err).ShouldNot(HaveOccurred()) - }) - - JustBeforeEach(func() { - cwd, err := os.Getwd() - Ω(err).ShouldNot(HaveOccurred()) - - relPath, err := filepath.Rel(cwd, filepath.Join(tmpDir, "convert_fixtures")) - Ω(err).ShouldNot(HaveOccurred()) - - cmd := exec.Command(pathToGinkgo, "convert", relPath) - cmd.Env = os.Environ() - for i, env := range cmd.Env { - if strings.HasPrefix(env, "PATH") { - cmd.Env[i] = cmd.Env[i] + ":" + filepath.Dir(pathToGinkgo) - break - } - } - err = cmd.Run() - Ω(err).ShouldNot(HaveOccurred()) - }) - - AfterEach(func() { - err := os.RemoveAll(tmpDir) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("rewrites xunit tests as ginkgo tests", func() { - convertedFile := readConvertedFileNamed("xunit_test.go") - goldMaster := readGoldMasterNamed("xunit_test.go") - Ω(convertedFile).Should(Equal(goldMaster)) - }) - - It("rewrites all usages of *testing.T as mr.T()", func() { - convertedFile := readConvertedFileNamed("extra_functions_test.go") - goldMaster := readGoldMasterNamed("extra_functions_test.go") - Ω(convertedFile).Should(Equal(goldMaster)) - }) - - It("rewrites tests in the package dir that belong to other packages", func() { - convertedFile := readConvertedFileNamed("outside_package_test.go") - goldMaster := readGoldMasterNamed("outside_package_test.go") - Ω(convertedFile).Should(Equal(goldMaster)) - }) - - It("rewrites tests in nested packages", func() { - convertedFile := readConvertedFileNamed("nested", "nested_test.go") - goldMaster := readGoldMasterNamed("nested_test.go") - Ω(convertedFile).Should(Equal(goldMaster)) - }) - - Context("ginkgo test suite files", func() { - It("creates a ginkgo test suite file for the package you specified", func() { - testsuite := readConvertedFileNamed("convert_fixtures_suite_test.go") - goldMaster := readGoldMasterNamed("suite_test.go") - Ω(testsuite).Should(Equal(goldMaster)) - }) - - It("converts go tests in deeply nested packages (some may not contain go files)", func() { - testsuite := readConvertedFileNamed("nested_without_gofiles", "subpackage", "nested_subpackage_test.go") - goldMaster := readGoldMasterNamed("nested_subpackage_test.go") - Ω(testsuite).Should(Equal(goldMaster)) - }) - - It("creates ginkgo test suites for all nested packages", func() { - testsuite := readConvertedFileNamed("nested", "nested_suite_test.go") - goldMaster := readGoldMasterNamed("nested_suite_test.go") - Ω(testsuite).Should(Equal(goldMaster)) - }) - }) - - Context("with an existing test suite file", func() { - BeforeEach(func() { - goldMaster := readGoldMasterNamed("fixtures_suite_test.go") - err := ioutil.WriteFile(filepath.Join(tmpDir, "convert_fixtures", "tmp_suite_test.go"), []byte(goldMaster), 0600) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("gracefully handles existing test suite files", func() { - //nothing should have gone wrong! - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/coverage_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/coverage_test.go deleted file mode 100644 index 4a20b0d..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/coverage_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package integration_test - -import ( - "os" - "os/exec" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Coverage Specs", func() { - AfterEach(func() { - os.RemoveAll("./_fixtures/coverage_fixture/coverage_fixture.coverprofile") - }) - - It("runs coverage analysis in series and in parallel", func() { - session := startGinkgo("./_fixtures/coverage_fixture", "-cover") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - Ω(output).Should(ContainSubstring("coverage: 80.0% of statements")) - - serialCoverProfileOutput, err := exec.Command("go", "tool", "cover", "-func=./_fixtures/coverage_fixture/coverage_fixture.coverprofile").CombinedOutput() - Ω(err).ShouldNot(HaveOccurred()) - - os.RemoveAll("./_fixtures/coverage_fixture/coverage_fixture.coverprofile") - - Eventually(startGinkgo("./_fixtures/coverage_fixture", "-cover", "-nodes=4")).Should(gexec.Exit(0)) - - parallelCoverProfileOutput, err := exec.Command("go", "tool", "cover", "-func=./_fixtures/coverage_fixture/coverage_fixture.coverprofile").CombinedOutput() - Ω(err).ShouldNot(HaveOccurred()) - - Ω(parallelCoverProfileOutput).Should(Equal(serialCoverProfileOutput)) - }) - - It("runs coverage analysis on external packages in series and in parallel", func() { - session := startGinkgo("./_fixtures/coverage_fixture", "-coverpkg=github.com/onsi/ginkgo/integration/_fixtures/coverage_fixture,github.com/onsi/ginkgo/integration/_fixtures/coverage_fixture/external_coverage_fixture") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - Ω(output).Should(ContainSubstring("coverage: 71.4% of statements in github.com/onsi/ginkgo/integration/_fixtures/coverage_fixture, github.com/onsi/ginkgo/integration/_fixtures/coverage_fixture/external_coverage_fixture")) - - serialCoverProfileOutput, err := exec.Command("go", "tool", "cover", "-func=./_fixtures/coverage_fixture/coverage_fixture.coverprofile").CombinedOutput() - Ω(err).ShouldNot(HaveOccurred()) - - os.RemoveAll("./_fixtures/coverage_fixture/coverage_fixture.coverprofile") - - Eventually(startGinkgo("./_fixtures/coverage_fixture", "-coverpkg=github.com/onsi/ginkgo/integration/_fixtures/coverage_fixture,github.com/onsi/ginkgo/integration/_fixtures/coverage_fixture/external_coverage_fixture", "-nodes=4")).Should(gexec.Exit(0)) - - parallelCoverProfileOutput, err := exec.Command("go", "tool", "cover", "-func=./_fixtures/coverage_fixture/coverage_fixture.coverprofile").CombinedOutput() - Ω(err).ShouldNot(HaveOccurred()) - - Ω(parallelCoverProfileOutput).Should(Equal(serialCoverProfileOutput)) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/fail_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/fail_test.go deleted file mode 100644 index 8dcf5e4..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/fail_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package integration_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Failing Specs", func() { - var pathToTest string - - BeforeEach(func() { - pathToTest = tmpPath("failing") - copyIn("fail_fixture", pathToTest) - }) - - It("should fail in all the possible ways", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(output).ShouldNot(ContainSubstring("NEVER SEE THIS")) - - Ω(output).Should(ContainSubstring("a top level failure on line 9")) - Ω(output).Should(ContainSubstring("fail_fixture_test.go:9")) - Ω(output).Should(ContainSubstring("an async top level failure on line 14")) - Ω(output).Should(ContainSubstring("fail_fixture_test.go:14")) - Ω(output).Should(ContainSubstring("a top level goroutine failure on line 21")) - Ω(output).Should(ContainSubstring("fail_fixture_test.go:21")) - - Ω(output).Should(ContainSubstring("a sync failure")) - Ω(output).Should(MatchRegexp(`Test Panicked\n\s+a sync panic`)) - Ω(output).Should(ContainSubstring("a sync FAIL failure")) - Ω(output).Should(ContainSubstring("async timeout [It]")) - Ω(output).Should(ContainSubstring("Timed out")) - Ω(output).Should(ContainSubstring("an async failure")) - Ω(output).Should(MatchRegexp(`Test Panicked\n\s+an async panic`)) - Ω(output).Should(ContainSubstring("an async FAIL failure")) - Ω(output).Should(ContainSubstring("a goroutine FAIL failure")) - Ω(output).Should(ContainSubstring("a goroutine failure")) - Ω(output).Should(MatchRegexp(`Test Panicked\n\s+a goroutine panic`)) - Ω(output).Should(ContainSubstring("a measure failure")) - Ω(output).Should(ContainSubstring("a measure FAIL failure")) - Ω(output).Should(MatchRegexp(`Test Panicked\n\s+a measure panic`)) - - Ω(output).Should(ContainSubstring("0 Passed | 16 Failed")) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/flags_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/flags_test.go deleted file mode 100644 index 0a23f59..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/flags_test.go +++ /dev/null @@ -1,176 +0,0 @@ -package integration_test - -import ( - "os" - "path/filepath" - "strings" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Flags Specs", func() { - var pathToTest string - - BeforeEach(func() { - pathToTest = tmpPath("flags") - copyIn("flags_tests", pathToTest) - }) - - getRandomOrders := func(output string) []int { - return []int{strings.Index(output, "RANDOM_A"), strings.Index(output, "RANDOM_B"), strings.Index(output, "RANDOM_C")} - } - - It("normally passes, runs measurements, prints out noisy pendings, does not randomize tests, and honors the programmatic focus", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Ran 3 samples:"), "has a measurement") - Ω(output).Should(ContainSubstring("10 Passed")) - Ω(output).Should(ContainSubstring("0 Failed")) - Ω(output).Should(ContainSubstring("1 Pending")) - Ω(output).Should(ContainSubstring("2 Skipped")) - Ω(output).Should(ContainSubstring("[PENDING]")) - Ω(output).Should(ContainSubstring("marshmallow")) - Ω(output).Should(ContainSubstring("chocolate")) - Ω(output).Should(ContainSubstring("CUSTOM_FLAG: default")) - Ω(output).Should(ContainSubstring("Detected Programmatic Focus - setting exit status to %d", types.GINKGO_FOCUS_EXIT_CODE)) - Ω(output).ShouldNot(ContainSubstring("smores")) - Ω(output).ShouldNot(ContainSubstring("SLOW TEST")) - Ω(output).ShouldNot(ContainSubstring("should honor -slowSpecThreshold")) - - orders := getRandomOrders(output) - Ω(orders[0]).Should(BeNumerically("<", orders[1])) - Ω(orders[1]).Should(BeNumerically("<", orders[2])) - }) - - It("should run a coverprofile when passed -cover", func() { - session := startGinkgo(pathToTest, "--noColor", "--cover", "--focus=the focused set") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - _, err := os.Stat(filepath.Join(pathToTest, "flags.coverprofile")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(output).Should(ContainSubstring("coverage: ")) - }) - - It("should fail when there are pending tests and it is passed --failOnPending", func() { - session := startGinkgo(pathToTest, "--noColor", "--failOnPending") - Eventually(session).Should(gexec.Exit(1)) - }) - - It("should not print out pendings when --noisyPendings=false", func() { - session := startGinkgo(pathToTest, "--noColor", "--noisyPendings=false") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).ShouldNot(ContainSubstring("[PENDING]")) - Ω(output).Should(ContainSubstring("1 Pending")) - }) - - It("should override the programmatic focus when told to focus", func() { - session := startGinkgo(pathToTest, "--noColor", "--focus=smores") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("marshmallow")) - Ω(output).Should(ContainSubstring("chocolate")) - Ω(output).Should(ContainSubstring("smores")) - Ω(output).Should(ContainSubstring("3 Passed")) - Ω(output).Should(ContainSubstring("0 Failed")) - Ω(output).Should(ContainSubstring("0 Pending")) - Ω(output).Should(ContainSubstring("10 Skipped")) - }) - - It("should override the programmatic focus when told to skip", func() { - session := startGinkgo(pathToTest, "--noColor", "--skip=marshmallow|failing") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).ShouldNot(ContainSubstring("marshmallow")) - Ω(output).Should(ContainSubstring("chocolate")) - Ω(output).Should(ContainSubstring("smores")) - Ω(output).Should(ContainSubstring("10 Passed")) - Ω(output).Should(ContainSubstring("0 Failed")) - Ω(output).Should(ContainSubstring("1 Pending")) - Ω(output).Should(ContainSubstring("2 Skipped")) - }) - - It("should run the race detector when told to", func() { - session := startGinkgo(pathToTest, "--noColor", "--race") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("WARNING: DATA RACE")) - }) - - It("should randomize tests when told to", func() { - session := startGinkgo(pathToTest, "--noColor", "--randomizeAllSpecs", "--seed=21") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - orders := getRandomOrders(output) - Ω(orders[0]).ShouldNot(BeNumerically("<", orders[1])) - }) - - It("should skip measurements when told to", func() { - session := startGinkgo(pathToTest, "--skipMeasurements") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).ShouldNot(ContainSubstring("Ran 3 samples:"), "has a measurement") - Ω(output).Should(ContainSubstring("3 Skipped")) - }) - - It("should watch for slow specs", func() { - session := startGinkgo(pathToTest, "--slowSpecThreshold=0.05") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("SLOW TEST")) - Ω(output).Should(ContainSubstring("should honor -slowSpecThreshold")) - }) - - It("should pass additional arguments in", func() { - session := startGinkgo(pathToTest, "--", "--customFlag=madagascar") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("CUSTOM_FLAG: madagascar")) - }) - - It("should print out full stack traces for failures when told to", func() { - session := startGinkgo(pathToTest, "--focus=a failing test", "--trace") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Full Stack Trace")) - }) - - It("should fail fast when told to", func() { - pathToTest = tmpPath("fail") - copyIn("fail_fixture", pathToTest) - session := startGinkgo(pathToTest, "--failFast") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("1 Failed")) - Ω(output).Should(ContainSubstring("15 Skipped")) - }) - - It("should perform a dry run when told to", func() { - pathToTest = tmpPath("fail") - copyIn("fail_fixture", pathToTest) - session := startGinkgo(pathToTest, "--dryRun", "-v") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("synchronous failures")) - Ω(output).Should(ContainSubstring("16 Specs")) - Ω(output).Should(ContainSubstring("0 Passed")) - Ω(output).Should(ContainSubstring("0 Failed")) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/integration.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/integration.go deleted file mode 100644 index 76ab1b7..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/integration.go +++ /dev/null @@ -1 +0,0 @@ -package integration diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/integration_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/integration_suite_test.go deleted file mode 100644 index 0ad407c..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/integration_suite_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package integration_test - -import ( - "io" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" - - "testing" - "time" -) - -var tmpDir string -var pathToGinkgo string - -func TestIntegration(t *testing.T) { - SetDefaultEventuallyTimeout(15 * time.Second) - RegisterFailHandler(Fail) - RunSpecs(t, "Integration Suite") -} - -var _ = SynchronizedBeforeSuite(func() []byte { - pathToGinkgo, err := gexec.Build("github.com/onsi/ginkgo/ginkgo") - Ω(err).ShouldNot(HaveOccurred()) - return []byte(pathToGinkgo) -}, func(computedPathToGinkgo []byte) { - pathToGinkgo = string(computedPathToGinkgo) -}) - -var _ = BeforeEach(func() { - var err error - tmpDir, err = ioutil.TempDir("", "ginkgo-run") - Ω(err).ShouldNot(HaveOccurred()) -}) - -var _ = AfterEach(func() { - err := os.RemoveAll(tmpDir) - Ω(err).ShouldNot(HaveOccurred()) -}) - -var _ = SynchronizedAfterSuite(func() {}, func() { - gexec.CleanupBuildArtifacts() -}) - -func tmpPath(destination string) string { - return filepath.Join(tmpDir, destination) -} - -func copyIn(fixture string, destination string) { - err := os.MkdirAll(destination, 0777) - Ω(err).ShouldNot(HaveOccurred()) - - filepath.Walk(filepath.Join("_fixtures", fixture), func(path string, info os.FileInfo, err error) error { - if info.IsDir() { - return nil - } - - base := filepath.Base(path) - - src, err := os.Open(path) - Ω(err).ShouldNot(HaveOccurred()) - - dst, err := os.Create(filepath.Join(destination, base)) - Ω(err).ShouldNot(HaveOccurred()) - - _, err = io.Copy(dst, src) - Ω(err).ShouldNot(HaveOccurred()) - return nil - }) -} - -func ginkgoCommand(dir string, args ...string) *exec.Cmd { - cmd := exec.Command(pathToGinkgo, args...) - cmd.Dir = dir - - return cmd -} - -func startGinkgo(dir string, args ...string) *gexec.Session { - cmd := ginkgoCommand(dir, args...) - session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - return session -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/interrupt_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/interrupt_test.go deleted file mode 100644 index dc3bf28..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/interrupt_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package integration_test - -import ( - "os/exec" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Interrupt", func() { - var pathToTest string - BeforeEach(func() { - pathToTest = tmpPath("hanging") - copyIn("hanging_suite", pathToTest) - }) - - Context("when interrupting a suite", func() { - var session *gexec.Session - BeforeEach(func() { - //we need to signal the actual process, so we must compile the test first - var err error - cmd := exec.Command("go", "test", "-c") - cmd.Dir = pathToTest - session, err = gexec.Start(cmd, GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - Eventually(session).Should(gexec.Exit(0)) - - //then run the compiled test directly - cmd = exec.Command("./hanging.test", "--test.v=true", "--ginkgo.noColor") - cmd.Dir = pathToTest - session, err = gexec.Start(cmd, GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - - Eventually(session).Should(gbytes.Say("Sleeping...")) - session.Interrupt() - Eventually(session, 1000).Should(gexec.Exit(1)) - }) - - It("should emit the contents of the GinkgoWriter", func() { - Ω(session).Should(gbytes.Say("Just beginning")) - Ω(session).Should(gbytes.Say("Almost there...")) - Ω(session).Should(gbytes.Say("Hanging Out")) - }) - - It("should run the AfterSuite", func() { - Ω(session).Should(gbytes.Say("Heading Out After Suite")) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/precompiled_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/precompiled_test.go deleted file mode 100644 index d9b78e0..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/precompiled_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package integration_test - -import ( - "os" - "os/exec" - "path/filepath" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("ginkgo build", func() { - var pathToTest string - - BeforeEach(func() { - pathToTest = tmpPath("passing_ginkgo_tests") - copyIn("passing_ginkgo_tests", pathToTest) - session := startGinkgo(pathToTest, "build") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - Ω(output).Should(ContainSubstring("Compiling passing_ginkgo_tests")) - Ω(output).Should(ContainSubstring("compiled passing_ginkgo_tests.test")) - }) - - It("should build a test binary", func() { - _, err := os.Stat(filepath.Join(pathToTest, "passing_ginkgo_tests.test")) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("should be possible to run the test binary directly", func() { - cmd := exec.Command("./passing_ginkgo_tests.test") - cmd.Dir = pathToTest - session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - Eventually(session).Should(gexec.Exit(0)) - Ω(session).Should(gbytes.Say("Running Suite: Passing_ginkgo_tests Suite")) - }) - - It("should be possible to run the test binary via ginkgo", func() { - session := startGinkgo(pathToTest, "./passing_ginkgo_tests.test") - Eventually(session).Should(gexec.Exit(0)) - Ω(session).Should(gbytes.Say("Running Suite: Passing_ginkgo_tests Suite")) - }) - - It("should be possible to run the test binary in parallel", func() { - session := startGinkgo(pathToTest, "--nodes=4", "--noColor", "./passing_ginkgo_tests.test") - Eventually(session).Should(gexec.Exit(0)) - Ω(session).Should(gbytes.Say("Running Suite: Passing_ginkgo_tests Suite")) - Ω(session).Should(gbytes.Say("Running in parallel across 4 nodes")) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/progress_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/progress_test.go deleted file mode 100644 index 8589c33..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/progress_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package integration_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Emitting progress", func() { - var pathToTest string - var session *gexec.Session - var args []string - - BeforeEach(func() { - args = []string{"--noColor"} - pathToTest = tmpPath("progress") - copyIn("progress_fixture", pathToTest) - }) - - JustBeforeEach(func() { - session = startGinkgo(pathToTest, args...) - Eventually(session).Should(gexec.Exit(0)) - }) - - Context("with the -progress flag, but no -v flag", func() { - BeforeEach(func() { - args = append(args, "-progress") - }) - - It("should not emit progress", func() { - Ω(session).ShouldNot(gbytes.Say("[bB]efore")) - }) - }) - - Context("with the -v flag", func() { - BeforeEach(func() { - args = append(args, "-v") - }) - - It("should not emit progress", func() { - Ω(session).ShouldNot(gbytes.Say(`\[BeforeEach\]`)) - Ω(session).Should(gbytes.Say(`>outer before<`)) - }) - }) - - Context("with the -progress flag and the -v flag", func() { - BeforeEach(func() { - args = append(args, "-progress", "-v") - }) - - It("should emit progress (by writing to the GinkgoWriter)", func() { - Ω(session).Should(gbytes.Say(`\[BeforeEach\] ProgressFixture`)) - Ω(session).Should(gbytes.Say(`>outer before<`)) - - Ω(session).Should(gbytes.Say(`\[BeforeEach\] Inner Context`)) - Ω(session).Should(gbytes.Say(`>inner before<`)) - - Ω(session).Should(gbytes.Say(`\[JustBeforeEach\] ProgressFixture`)) - Ω(session).Should(gbytes.Say(`>outer just before<`)) - - Ω(session).Should(gbytes.Say(`\[JustBeforeEach\] Inner Context`)) - Ω(session).Should(gbytes.Say(`>inner just before<`)) - - Ω(session).Should(gbytes.Say(`\[It\] should emit progress as it goes`)) - Ω(session).Should(gbytes.Say(`>it<`)) - - Ω(session).Should(gbytes.Say(`\[AfterEach\] Inner Context`)) - Ω(session).Should(gbytes.Say(`>inner after<`)) - - Ω(session).Should(gbytes.Say(`\[AfterEach\] ProgressFixture`)) - Ω(session).Should(gbytes.Say(`>outer after<`)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/run_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/run_test.go deleted file mode 100644 index c346bb3..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/run_test.go +++ /dev/null @@ -1,373 +0,0 @@ -package integration_test - -import ( - "runtime" - "strings" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Running Specs", func() { - var pathToTest string - - Context("when pointed at the current directory", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - copyIn("passing_ginkgo_tests", pathToTest) - }) - - It("should run the tests in the working directory", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("••••")) - Ω(output).Should(ContainSubstring("SUCCESS! -- 4 Passed")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("when passed an explicit package to run", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - copyIn("passing_ginkgo_tests", pathToTest) - }) - - It("should run the ginkgo style tests", func() { - session := startGinkgo(tmpDir, "--noColor", pathToTest) - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("••••")) - Ω(output).Should(ContainSubstring("SUCCESS! -- 4 Passed")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("when passed a number of packages to run", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - otherPathToTest := tmpPath("other") - copyIn("passing_ginkgo_tests", pathToTest) - copyIn("more_ginkgo_tests", otherPathToTest) - }) - - It("should run the ginkgo style tests", func() { - session := startGinkgo(tmpDir, "--noColor", "--succinct=false", "ginkgo", "./other") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("when passed a number of packages to run, some of which have focused tests", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - otherPathToTest := tmpPath("other") - focusedPathToTest := tmpPath("focused") - copyIn("passing_ginkgo_tests", pathToTest) - copyIn("more_ginkgo_tests", otherPathToTest) - copyIn("focused_fixture", focusedPathToTest) - }) - - It("should exit with a status code of 2 and explain why", func() { - session := startGinkgo(tmpDir, "--noColor", "--succinct=false", "-r") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - Ω(output).Should(ContainSubstring("Detected Programmatic Focus - setting exit status to %d", types.GINKGO_FOCUS_EXIT_CODE)) - }) - }) - - Context("when told to skipPackages", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - otherPathToTest := tmpPath("other") - focusedPathToTest := tmpPath("focused") - copyIn("passing_ginkgo_tests", pathToTest) - copyIn("more_ginkgo_tests", otherPathToTest) - copyIn("focused_fixture", focusedPathToTest) - }) - - It("should skip packages that match the list", func() { - session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused", "-r") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Passing_ginkgo_tests Suite")) - Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite")) - Ω(output).ShouldNot(ContainSubstring("Focused_fixture Suite")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - - Context("when all packages are skipped", func() { - It("should not run anything, but still exit 0", func() { - session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused,ginkgo", "-r") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("All tests skipped!")) - Ω(output).ShouldNot(ContainSubstring("Passing_ginkgo_tests Suite")) - Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite")) - Ω(output).ShouldNot(ContainSubstring("Focused_fixture Suite")) - Ω(output).ShouldNot(ContainSubstring("Test Suite Passed")) - }) - }) - }) - - Context("when there are no tests to run", func() { - It("should exit 1", func() { - session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused", "-r") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Err.Contents()) - - Ω(output).Should(ContainSubstring("Found no test suites")) - }) - }) - - Context("when told to randomizeSuites", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - otherPathToTest := tmpPath("other") - copyIn("passing_ginkgo_tests", pathToTest) - copyIn("more_ginkgo_tests", otherPathToTest) - }) - - It("should skip packages that match the regexp", func() { - session := startGinkgo(tmpDir, "--noColor", "--randomizeSuites", "-r", "--seed=2") - Eventually(session).Should(gexec.Exit(0)) - - Ω(session).Should(gbytes.Say("More_ginkgo_tests Suite")) - Ω(session).Should(gbytes.Say("Passing_ginkgo_tests Suite")) - - session = startGinkgo(tmpDir, "--noColor", "--randomizeSuites", "-r", "--seed=3") - Eventually(session).Should(gexec.Exit(0)) - - Ω(session).Should(gbytes.Say("Passing_ginkgo_tests Suite")) - Ω(session).Should(gbytes.Say("More_ginkgo_tests Suite")) - }) - }) - - Context("when pointed at a package with xunit style tests", func() { - BeforeEach(func() { - pathToTest = tmpPath("xunit") - copyIn("xunit_tests", pathToTest) - }) - - It("should run the xunit style tests", func() { - session := startGinkgo(pathToTest) - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("--- PASS: TestAlwaysTrue")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("when pointed at a package with no tests", func() { - BeforeEach(func() { - pathToTest = tmpPath("no_tests") - copyIn("no_tests", pathToTest) - }) - - It("should fail", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(1)) - - Ω(session.Err.Contents()).Should(ContainSubstring("Found no test suites")) - }) - }) - - Context("when pointed at a package that fails to compile", func() { - BeforeEach(func() { - pathToTest = tmpPath("does_not_compile") - copyIn("does_not_compile", pathToTest) - }) - - It("should fail", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Failed to compile")) - }) - }) - - Context("when running in parallel", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - copyIn("passing_ginkgo_tests", pathToTest) - }) - - Context("with a specific number of -nodes", func() { - It("should use the specified number of nodes", func() { - session := startGinkgo(pathToTest, "--noColor", "-succinct", "-nodes=2") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs - 2 nodes •••• SUCCESS! [\d.µs]+`)) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("with -p", func() { - It("it should autocompute the number of nodes", func() { - session := startGinkgo(pathToTest, "--noColor", "-succinct", "-p") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - nodes := runtime.NumCPU() - if nodes > 4 { - nodes = nodes - 1 - } - Ω(output).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs - %d nodes •••• SUCCESS! [\d.µs]+`, nodes)) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - }) - - Context("when streaming in parallel", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - copyIn("passing_ginkgo_tests", pathToTest) - }) - - It("should print output in realtime", func() { - session := startGinkgo(pathToTest, "--noColor", "-stream", "-nodes=2") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring(`[1] Parallel test node 1/2.`)) - Ω(output).Should(ContainSubstring(`[2] Parallel test node 2/2.`)) - Ω(output).Should(ContainSubstring(`[1] SUCCESS!`)) - Ω(output).Should(ContainSubstring(`[2] SUCCESS!`)) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("when running recursively", func() { - BeforeEach(func() { - passingTest := tmpPath("A") - otherPassingTest := tmpPath("E") - copyIn("passing_ginkgo_tests", passingTest) - copyIn("more_ginkgo_tests", otherPassingTest) - }) - - Context("when all the tests pass", func() { - It("should run all the tests (in succinct mode) and succeed", func() { - session := startGinkgo(tmpDir, "--noColor", "-r") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - outputLines := strings.Split(output, "\n") - Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs •••• SUCCESS! [\d.µs]+ PASS`)) - Ω(outputLines[1]).Should(MatchRegexp(`\[\d+\] More_ginkgo_tests Suite - 2/2 specs •• SUCCESS! [\d.µs]+ PASS`)) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("when one of the packages has a failing tests", func() { - BeforeEach(func() { - failingTest := tmpPath("C") - copyIn("failing_ginkgo_tests", failingTest) - }) - - It("should fail and stop running tests", func() { - session := startGinkgo(tmpDir, "--noColor", "-r") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - outputLines := strings.Split(output, "\n") - Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs •••• SUCCESS! [\d.µs]+ PASS`)) - Ω(outputLines[1]).Should(MatchRegexp(`\[\d+\] Failing_ginkgo_tests Suite - 2/2 specs`)) - Ω(output).Should(ContainSubstring("• Failure")) - Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Test Suite Failed")) - - Ω(output).Should(ContainSubstring("Summarizing 1 Failure:")) - Ω(output).Should(ContainSubstring("[Fail] FailingGinkgoTests [It] should fail")) - }) - }) - - Context("when one of the packages fails to compile", func() { - BeforeEach(func() { - doesNotCompileTest := tmpPath("C") - copyIn("does_not_compile", doesNotCompileTest) - }) - - It("should fail and stop running tests", func() { - session := startGinkgo(tmpDir, "--noColor", "-r") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - outputLines := strings.Split(output, "\n") - Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs •••• SUCCESS! [\d.µs]+ PASS`)) - Ω(outputLines[1]).Should(ContainSubstring("Failed to compile C:")) - Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Test Suite Failed")) - }) - }) - - Context("when either is the case, but the keepGoing flag is set", func() { - BeforeEach(func() { - doesNotCompileTest := tmpPath("B") - copyIn("does_not_compile", doesNotCompileTest) - - failingTest := tmpPath("C") - copyIn("failing_ginkgo_tests", failingTest) - }) - - It("should soldier on", func() { - session := startGinkgo(tmpDir, "--noColor", "-r", "-keepGoing") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - outputLines := strings.Split(output, "\n") - Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs •••• SUCCESS! [\d.µs]+ PASS`)) - Ω(outputLines[1]).Should(ContainSubstring("Failed to compile B:")) - Ω(output).Should(MatchRegexp(`\[\d+\] Failing_ginkgo_tests Suite - 2/2 specs`)) - Ω(output).Should(ContainSubstring("• Failure")) - Ω(output).Should(MatchRegexp(`\[\d+\] More_ginkgo_tests Suite - 2/2 specs •• SUCCESS! [\d.µs]+ PASS`)) - Ω(output).Should(ContainSubstring("Test Suite Failed")) - }) - }) - }) - - Context("when told to keep going --untilItFails", func() { - BeforeEach(func() { - copyIn("eventually_failing", tmpDir) - }) - - It("should keep rerunning the tests, until a failure occurs", func() { - session := startGinkgo(tmpDir, "--untilItFails", "--noColor") - Eventually(session).Should(gexec.Exit(1)) - Ω(session).Should(gbytes.Say("This was attempt #1")) - Ω(session).Should(gbytes.Say("This was attempt #2")) - Ω(session).Should(gbytes.Say("Tests failed on attempt #3")) - - //it should change the random seed between each test - lines := strings.Split(string(session.Out.Contents()), "\n") - randomSeeds := []string{} - for _, line := range lines { - if strings.Contains(line, "Random Seed:") { - randomSeeds = append(randomSeeds, strings.Split(line, ": ")[1]) - } - } - Ω(randomSeeds[0]).ShouldNot(Equal(randomSeeds[1])) - Ω(randomSeeds[1]).ShouldNot(Equal(randomSeeds[2])) - Ω(randomSeeds[0]).ShouldNot(Equal(randomSeeds[2])) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/subcommand_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/subcommand_test.go deleted file mode 100644 index 32dfa0e..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/subcommand_test.go +++ /dev/null @@ -1,364 +0,0 @@ -package integration_test - -import ( - "io/ioutil" - "os" - "path/filepath" - "strings" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Subcommand", func() { - Describe("ginkgo bootstrap", func() { - var pkgPath string - BeforeEach(func() { - pkgPath = tmpPath("foo") - os.Mkdir(pkgPath, 0777) - }) - - It("should generate a bootstrap file, as long as one does not exist", func() { - session := startGinkgo(pkgPath, "bootstrap") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_suite_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_test")) - Ω(content).Should(ContainSubstring("func TestFoo(t *testing.T) {")) - Ω(content).Should(ContainSubstring("RegisterFailHandler")) - Ω(content).Should(ContainSubstring("RunSpecs")) - - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/ginkgo"`)) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/gomega"`)) - - session = startGinkgo(pkgPath, "bootstrap") - Eventually(session).Should(gexec.Exit(1)) - output = session.Out.Contents() - Ω(output).Should(ContainSubstring("foo_suite_test.go already exists")) - }) - - It("should import nodot declarations when told to", func() { - session := startGinkgo(pkgPath, "bootstrap", "--nodot") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_suite_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_test")) - Ω(content).Should(ContainSubstring("func TestFoo(t *testing.T) {")) - Ω(content).Should(ContainSubstring("RegisterFailHandler")) - Ω(content).Should(ContainSubstring("RunSpecs")) - - Ω(content).Should(ContainSubstring("var It = ginkgo.It")) - Ω(content).Should(ContainSubstring("var Ω = gomega.Ω")) - - Ω(content).Should(ContainSubstring("\t" + `"github.com/onsi/ginkgo"`)) - Ω(content).Should(ContainSubstring("\t" + `"github.com/onsi/gomega"`)) - }) - - It("should generate an agouti bootstrap file when told to", func() { - session := startGinkgo(pkgPath, "bootstrap", "--agouti") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_suite_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_test")) - Ω(content).Should(ContainSubstring("func TestFoo(t *testing.T) {")) - Ω(content).Should(ContainSubstring("RegisterFailHandler")) - Ω(content).Should(ContainSubstring("RunSpecs")) - - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/ginkgo"`)) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/gomega"`)) - Ω(content).Should(ContainSubstring("\t" + `"github.com/sclevine/agouti"`)) - }) - }) - - Describe("nodot", func() { - It("should update the declarations in the bootstrap file", func() { - pkgPath := tmpPath("foo") - os.Mkdir(pkgPath, 0777) - - session := startGinkgo(pkgPath, "bootstrap", "--nodot") - Eventually(session).Should(gexec.Exit(0)) - - byteContent, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - - content := string(byteContent) - content = strings.Replace(content, "var It =", "var MyIt =", -1) - content = strings.Replace(content, "var Ω = gomega.Ω\n", "", -1) - - err = ioutil.WriteFile(filepath.Join(pkgPath, "foo_suite_test.go"), []byte(content), os.ModePerm) - Ω(err).ShouldNot(HaveOccurred()) - - session = startGinkgo(pkgPath, "nodot") - Eventually(session).Should(gexec.Exit(0)) - - byteContent, err = ioutil.ReadFile(filepath.Join(pkgPath, "foo_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(byteContent).Should(ContainSubstring("var MyIt = ginkgo.It")) - Ω(byteContent).ShouldNot(ContainSubstring("var It = ginkgo.It")) - Ω(byteContent).Should(ContainSubstring("var Ω = gomega.Ω")) - }) - }) - - Describe("ginkgo generate", func() { - var pkgPath string - - BeforeEach(func() { - pkgPath = tmpPath("foo_bar") - os.Mkdir(pkgPath, 0777) - }) - - Context("with no arguments", func() { - It("should generate a test file named after the package", func() { - session := startGinkgo(pkgPath, "generate") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_bar_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_bar_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("FooBar", func() {`)) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/ginkgo"`)) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/gomega"`)) - - session = startGinkgo(pkgPath, "generate") - Eventually(session).Should(gexec.Exit(1)) - output = session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_bar_test.go already exists")) - }) - }) - - Context("with an argument of the form: foo", func() { - It("should generate a test file named after the argument", func() { - session := startGinkgo(pkgPath, "generate", "baz_buzz") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("baz_buzz_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "baz_buzz_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("BazBuzz", func() {`)) - }) - }) - - Context("with an argument of the form: foo.go", func() { - It("should generate a test file named after the argument", func() { - session := startGinkgo(pkgPath, "generate", "baz_buzz.go") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("baz_buzz_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "baz_buzz_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("BazBuzz", func() {`)) - - }) - }) - - Context("with an argument of the form: foo_test", func() { - It("should generate a test file named after the argument", func() { - session := startGinkgo(pkgPath, "generate", "baz_buzz_test") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("baz_buzz_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "baz_buzz_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("BazBuzz", func() {`)) - }) - }) - - Context("with an argument of the form: foo_test.go", func() { - It("should generate a test file named after the argument", func() { - session := startGinkgo(pkgPath, "generate", "baz_buzz_test.go") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("baz_buzz_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "baz_buzz_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("BazBuzz", func() {`)) - }) - }) - - Context("with multiple arguments", func() { - It("should generate a test file named after the argument", func() { - session := startGinkgo(pkgPath, "generate", "baz", "buzz") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("baz_test.go")) - Ω(output).Should(ContainSubstring("buzz_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "baz_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("Baz", func() {`)) - - content, err = ioutil.ReadFile(filepath.Join(pkgPath, "buzz_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("Buzz", func() {`)) - }) - }) - - Context("with nodot", func() { - It("should not import ginkgo or gomega", func() { - session := startGinkgo(pkgPath, "generate", "--nodot") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_bar_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_bar_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).ShouldNot(ContainSubstring("\t" + `. "github.com/onsi/ginkgo"`)) - Ω(content).ShouldNot(ContainSubstring("\t" + `. "github.com/onsi/gomega"`)) - }) - }) - - Context("with agouti", func() { - It("should generate an agouti test file", func() { - session := startGinkgo(pkgPath, "generate", "--agouti") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_bar_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_bar_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/ginkgo"`)) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/gomega"`)) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/sclevine/agouti/matchers"`)) - Ω(content).Should(ContainSubstring("\t" + `"github.com/sclevine/agouti"`)) - Ω(content).Should(ContainSubstring("page, err = agoutiDriver.NewPage()")) - }) - }) - }) - - Describe("ginkgo bootstrap/generate", func() { - var pkgPath string - BeforeEach(func() { - pkgPath = tmpPath("some crazy-thing") - os.Mkdir(pkgPath, 0777) - }) - - Context("when the working directory is empty", func() { - It("generates correctly named bootstrap and generate files with a package name derived from the directory", func() { - session := startGinkgo(pkgPath, "bootstrap") - Eventually(session).Should(gexec.Exit(0)) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "some_crazy_thing_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package some_crazy_thing_test")) - Ω(content).Should(ContainSubstring("SomeCrazyThing Suite")) - - session = startGinkgo(pkgPath, "generate") - Eventually(session).Should(gexec.Exit(0)) - - content, err = ioutil.ReadFile(filepath.Join(pkgPath, "some_crazy_thing_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package some_crazy_thing_test")) - Ω(content).Should(ContainSubstring("SomeCrazyThing")) - }) - }) - - Context("when the working directory contains a file with a package name", func() { - BeforeEach(func() { - Ω(ioutil.WriteFile(filepath.Join(pkgPath, "foo.go"), []byte("package main\n\nfunc main() {}"), 0777)).Should(Succeed()) - }) - - It("generates correctly named bootstrap and generate files with the package name", func() { - session := startGinkgo(pkgPath, "bootstrap") - Eventually(session).Should(gexec.Exit(0)) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "some_crazy_thing_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package main_test")) - Ω(content).Should(ContainSubstring("SomeCrazyThing Suite")) - - session = startGinkgo(pkgPath, "generate") - Eventually(session).Should(gexec.Exit(0)) - - content, err = ioutil.ReadFile(filepath.Join(pkgPath, "some_crazy_thing_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package main_test")) - Ω(content).Should(ContainSubstring("SomeCrazyThing")) - }) - }) - }) - - Describe("ginkgo blur", func() { - It("should unfocus tests", func() { - pathToTest := tmpPath("focused") - copyIn("focused_fixture", pathToTest) - - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("3 Passed")) - Ω(output).Should(ContainSubstring("3 Skipped")) - - session = startGinkgo(pathToTest, "blur") - Eventually(session).Should(gexec.Exit(0)) - - session = startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output = session.Out.Contents() - Ω(output).Should(ContainSubstring("6 Passed")) - Ω(output).Should(ContainSubstring("0 Skipped")) - }) - }) - - Describe("ginkgo version", func() { - It("should print out the version info", func() { - session := startGinkgo("", "version") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(MatchRegexp(`Ginkgo Version \d+\.\d+\.\d+`)) - }) - }) - - Describe("ginkgo help", func() { - It("should print out usage information", func() { - session := startGinkgo("", "help") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Err.Contents()) - - Ω(output).Should(MatchRegexp(`Ginkgo Version \d+\.\d+\.\d+`)) - Ω(output).Should(ContainSubstring("ginkgo watch")) - Ω(output).Should(ContainSubstring("-succinct")) - Ω(output).Should(ContainSubstring("-nodes")) - Ω(output).Should(ContainSubstring("ginkgo generate")) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/suite_setup_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/suite_setup_test.go deleted file mode 100644 index b9313db..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/suite_setup_test.go +++ /dev/null @@ -1,178 +0,0 @@ -package integration_test - -import ( - "strings" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("SuiteSetup", func() { - var pathToTest string - - Context("when the BeforeSuite and AfterSuite pass", func() { - BeforeEach(func() { - pathToTest = tmpPath("suite_setup") - copyIn("passing_suite_setup", pathToTest) - }) - - It("should run the BeforeSuite once, then run all the tests", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(strings.Count(output, "BEFORE SUITE")).Should(Equal(1)) - Ω(strings.Count(output, "AFTER SUITE")).Should(Equal(1)) - }) - - It("should run the BeforeSuite once per parallel node, then run all the tests", func() { - session := startGinkgo(pathToTest, "--noColor", "--nodes=2") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(strings.Count(output, "BEFORE SUITE")).Should(Equal(2)) - Ω(strings.Count(output, "AFTER SUITE")).Should(Equal(2)) - }) - }) - - Context("when the BeforeSuite fails", func() { - BeforeEach(func() { - pathToTest = tmpPath("suite_setup") - copyIn("failing_before_suite", pathToTest) - }) - - It("should run the BeforeSuite once, none of the tests, but it should run the AfterSuite", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(strings.Count(output, "BEFORE SUITE")).Should(Equal(1)) - Ω(strings.Count(output, "Test Panicked")).Should(Equal(1)) - Ω(strings.Count(output, "AFTER SUITE")).Should(Equal(1)) - Ω(output).ShouldNot(ContainSubstring("NEVER SEE THIS")) - }) - - It("should run the BeforeSuite once per parallel node, none of the tests, but it should run the AfterSuite for each node", func() { - session := startGinkgo(pathToTest, "--noColor", "--nodes=2") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(strings.Count(output, "BEFORE SUITE")).Should(Equal(2)) - Ω(strings.Count(output, "Test Panicked")).Should(Equal(2)) - Ω(strings.Count(output, "AFTER SUITE")).Should(Equal(2)) - Ω(output).ShouldNot(ContainSubstring("NEVER SEE THIS")) - }) - }) - - Context("when the AfterSuite fails", func() { - BeforeEach(func() { - pathToTest = tmpPath("suite_setup") - copyIn("failing_after_suite", pathToTest) - }) - - It("should run the BeforeSuite once, none of the tests, but it should run the AfterSuite", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(strings.Count(output, "BEFORE SUITE")).Should(Equal(1)) - Ω(strings.Count(output, "AFTER SUITE")).Should(Equal(1)) - Ω(strings.Count(output, "Test Panicked")).Should(Equal(1)) - Ω(strings.Count(output, "A TEST")).Should(Equal(2)) - }) - - It("should run the BeforeSuite once per parallel node, none of the tests, but it should run the AfterSuite for each node", func() { - session := startGinkgo(pathToTest, "--noColor", "--nodes=2") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(strings.Count(output, "BEFORE SUITE")).Should(Equal(2)) - Ω(strings.Count(output, "AFTER SUITE")).Should(Equal(2)) - Ω(strings.Count(output, "Test Panicked")).Should(Equal(2)) - Ω(strings.Count(output, "A TEST")).Should(Equal(2)) - }) - }) - - Context("With passing synchronized before and after suites", func() { - BeforeEach(func() { - pathToTest = tmpPath("suite_setup") - copyIn("synchronized_setup_tests", pathToTest) - }) - - Context("when run with one node", func() { - It("should do all the work on that one node", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("BEFORE_A_1\nBEFORE_B_1: DATA")) - Ω(output).Should(ContainSubstring("AFTER_A_1\nAFTER_B_1")) - }) - }) - - Context("when run across multiple nodes", func() { - It("should run the first BeforeSuite function (BEFORE_A) on node 1, the second (BEFORE_B) on all the nodes, the first AfterSuite (AFTER_A) on all the nodes, and then the second (AFTER_B) on Node 1 *after* everything else is finished", func() { - session := startGinkgo(pathToTest, "--noColor", "--nodes=3") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("BEFORE_A_1")) - Ω(output).Should(ContainSubstring("BEFORE_B_1: DATA")) - Ω(output).Should(ContainSubstring("BEFORE_B_2: DATA")) - Ω(output).Should(ContainSubstring("BEFORE_B_3: DATA")) - - Ω(output).ShouldNot(ContainSubstring("BEFORE_A_2")) - Ω(output).ShouldNot(ContainSubstring("BEFORE_A_3")) - - Ω(output).Should(ContainSubstring("AFTER_A_1")) - Ω(output).Should(ContainSubstring("AFTER_A_2")) - Ω(output).Should(ContainSubstring("AFTER_A_3")) - Ω(output).Should(ContainSubstring("AFTER_B_1")) - - Ω(output).ShouldNot(ContainSubstring("AFTER_B_2")) - Ω(output).ShouldNot(ContainSubstring("AFTER_B_3")) - }) - }) - - Context("when streaming across multiple nodes", func() { - It("should run the first BeforeSuite function (BEFORE_A) on node 1, the second (BEFORE_B) on all the nodes, the first AfterSuite (AFTER_A) on all the nodes, and then the second (AFTER_B) on Node 1 *after* everything else is finished", func() { - session := startGinkgo(pathToTest, "--noColor", "--nodes=3", "--stream") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("[1] BEFORE_A_1")) - Ω(output).Should(ContainSubstring("[1] BEFORE_B_1: DATA")) - Ω(output).Should(ContainSubstring("[2] BEFORE_B_2: DATA")) - Ω(output).Should(ContainSubstring("[3] BEFORE_B_3: DATA")) - - Ω(output).ShouldNot(ContainSubstring("BEFORE_A_2")) - Ω(output).ShouldNot(ContainSubstring("BEFORE_A_3")) - - Ω(output).Should(ContainSubstring("[1] AFTER_A_1")) - Ω(output).Should(ContainSubstring("[2] AFTER_A_2")) - Ω(output).Should(ContainSubstring("[3] AFTER_A_3")) - Ω(output).Should(ContainSubstring("[1] AFTER_B_1")) - - Ω(output).ShouldNot(ContainSubstring("AFTER_B_2")) - Ω(output).ShouldNot(ContainSubstring("AFTER_B_3")) - }) - }) - }) - - Context("With a failing synchronized before suite", func() { - BeforeEach(func() { - pathToTest = tmpPath("suite_setup") - copyIn("exiting_synchronized_setup_tests", pathToTest) - }) - - It("should fail and let the user know that node 1 disappeared prematurely", func() { - session := startGinkgo(pathToTest, "--noColor", "--nodes=3") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Node 1 disappeared before completing BeforeSuite")) - Ω(output).Should(ContainSubstring("Ginkgo timed out waiting for all parallel nodes to report back!")) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/tags_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/tags_test.go deleted file mode 100644 index 626635b..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/tags_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package integration_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Tags", func() { - var pathToTest string - BeforeEach(func() { - pathToTest = tmpPath("tags") - copyIn("tags_tests", pathToTest) - }) - - It("should honor the passed in -tags flag", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - Ω(output).Should(ContainSubstring("Ran 1 of 1 Specs")) - - session = startGinkgo(pathToTest, "--noColor", "-tags=complex_tests") - Eventually(session).Should(gexec.Exit(0)) - output = string(session.Out.Contents()) - Ω(output).Should(ContainSubstring("Ran 3 of 3 Specs")) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/test_description_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/test_description_test.go deleted file mode 100644 index 70a8f04..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/test_description_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package integration_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("TestDescription", func() { - var pathToTest string - - BeforeEach(func() { - pathToTest = tmpPath("test_description") - copyIn("test_description", pathToTest) - }) - - It("should capture and emit information about the current test", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(1)) - - Ω(session).Should(gbytes.Say("TestDescription should pass:false")) - Ω(session).Should(gbytes.Say("TestDescription should fail:true")) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/verbose_and_succinct_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/verbose_and_succinct_test.go deleted file mode 100644 index 470affd..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/verbose_and_succinct_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package integration_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Verbose And Succinct Mode", func() { - var pathToTest string - var otherPathToTest string - - Context("when running one package", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - copyIn("passing_ginkgo_tests", pathToTest) - }) - - It("should default to non-succinct mode", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - }) - }) - - Context("when running more than one package", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - copyIn("passing_ginkgo_tests", pathToTest) - otherPathToTest = tmpPath("more_ginkgo") - copyIn("more_ginkgo_tests", otherPathToTest) - }) - - Context("with no flags set", func() { - It("should default to succinct mode", func() { - session := startGinkgo(pathToTest, "--noColor", pathToTest, otherPathToTest) - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("] Passing_ginkgo_tests Suite - 4/4 specs •••• SUCCESS!")) - Ω(output).Should(ContainSubstring("] More_ginkgo_tests Suite - 2/2 specs •• SUCCESS!")) - }) - }) - - Context("with --succinct=false", func() { - It("should not be in succinct mode", func() { - session := startGinkgo(pathToTest, "--noColor", "--succinct=false", pathToTest, otherPathToTest) - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite")) - }) - }) - - Context("with -v", func() { - It("should not be in succinct mode, but should be verbose", func() { - session := startGinkgo(pathToTest, "--noColor", "-v", pathToTest, otherPathToTest) - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("should proxy strings")) - Ω(output).Should(ContainSubstring("should always pass")) - }) - - It("should emit output from Bys", func() { - session := startGinkgo(pathToTest, "--noColor", "-v", pathToTest) - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("emitting one By")) - Ω(output).Should(ContainSubstring("emitting another By")) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/watch_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/watch_test.go deleted file mode 100644 index bbbcf36..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/watch_test.go +++ /dev/null @@ -1,239 +0,0 @@ -package integration_test - -import ( - "io/ioutil" - "os" - "path/filepath" - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Watch", func() { - var rootPath string - var pathA string - var pathB string - var pathC string - var session *gexec.Session - - BeforeEach(func() { - rootPath = tmpPath("root") - pathA = filepath.Join(rootPath, "src", "github.com", "onsi", "A") - pathB = filepath.Join(rootPath, "src", "github.com", "onsi", "B") - pathC = filepath.Join(rootPath, "src", "github.com", "onsi", "C") - - err := os.MkdirAll(pathA, 0700) - Ω(err).ShouldNot(HaveOccurred()) - - err = os.MkdirAll(pathB, 0700) - Ω(err).ShouldNot(HaveOccurred()) - - err = os.MkdirAll(pathC, 0700) - Ω(err).ShouldNot(HaveOccurred()) - - copyIn(filepath.Join("watch_fixtures", "A"), pathA) - copyIn(filepath.Join("watch_fixtures", "B"), pathB) - copyIn(filepath.Join("watch_fixtures", "C"), pathC) - }) - - startGinkgoWithGopath := func(args ...string) *gexec.Session { - cmd := ginkgoCommand(rootPath, args...) - cmd.Env = append([]string{"GOPATH=" + rootPath + ":" + os.Getenv("GOPATH")}, os.Environ()...) - session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - return session - } - - modifyFile := func(path string) { - time.Sleep(time.Second) - content, err := ioutil.ReadFile(path) - Ω(err).ShouldNot(HaveOccurred()) - content = append(content, []byte("//")...) - err = ioutil.WriteFile(path, content, 0666) - Ω(err).ShouldNot(HaveOccurred()) - } - - modifyCode := func(pkgToModify string) { - modifyFile(filepath.Join(rootPath, "src", "github.com", "onsi", pkgToModify, pkgToModify+".go")) - } - - modifyTest := func(pkgToModify string) { - modifyFile(filepath.Join(rootPath, "src", "github.com", "onsi", pkgToModify, pkgToModify+"_test.go")) - } - - AfterEach(func() { - if session != nil { - session.Kill().Wait() - } - }) - - It("should be set up correctly", func() { - session = startGinkgoWithGopath("-r") - Eventually(session).Should(gexec.Exit(0)) - Ω(session.Out.Contents()).Should(ContainSubstring("A Suite")) - Ω(session.Out.Contents()).Should(ContainSubstring("B Suite")) - Ω(session.Out.Contents()).Should(ContainSubstring("C Suite")) - Ω(session.Out.Contents()).Should(ContainSubstring("Ginkgo ran 3 suites")) - }) - - Context("when watching just one test suite", func() { - It("should immediately run, and should rerun when the test suite changes", func() { - session = startGinkgoWithGopath("watch", "-succinct", pathA) - Eventually(session).Should(gbytes.Say("A Suite")) - modifyCode("A") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("A Suite")) - session.Kill().Wait() - }) - }) - - Context("when watching several test suites", func() { - It("should not immediately run, but should rerun a test when its code changes", func() { - session = startGinkgoWithGopath("watch", "-succinct", "-r") - Eventually(session).Should(gbytes.Say("Identified 3 test suites")) - Consistently(session).ShouldNot(gbytes.Say("A Suite|B Suite|C Suite")) - modifyCode("A") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("B Suite|C Suite")) - session.Kill().Wait() - }) - }) - - Describe("watching dependencies", func() { - Context("with a depth of 2", func() { - It("should watch down to that depth", func() { - session = startGinkgoWithGopath("watch", "-succinct", "-r", "-depth=2") - Eventually(session).Should(gbytes.Say("Identified 3 test suites")) - Eventually(session).Should(gbytes.Say(`A \[2 dependencies\]`)) - Eventually(session).Should(gbytes.Say(`B \[1 dependency\]`)) - Eventually(session).Should(gbytes.Say(`C \[0 dependencies\]`)) - - modifyCode("A") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("B Suite|C Suite")) - - modifyCode("B") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("B Suite")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("C Suite")) - - modifyCode("C") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("C Suite")) - Eventually(session).Should(gbytes.Say("B Suite")) - Eventually(session).Should(gbytes.Say("A Suite")) - }) - }) - - Context("with a depth of 1", func() { - It("should watch down to that depth", func() { - session = startGinkgoWithGopath("watch", "-succinct", "-r", "-depth=1") - Eventually(session).Should(gbytes.Say("Identified 3 test suites")) - Eventually(session).Should(gbytes.Say(`A \[1 dependency\]`)) - Eventually(session).Should(gbytes.Say(`B \[1 dependency\]`)) - Eventually(session).Should(gbytes.Say(`C \[0 dependencies\]`)) - - modifyCode("A") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("B Suite|C Suite")) - - modifyCode("B") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("B Suite")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("C Suite")) - - modifyCode("C") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("C Suite")) - Eventually(session).Should(gbytes.Say("B Suite")) - Consistently(session).ShouldNot(gbytes.Say("A Suite")) - }) - }) - - Context("with a depth of 0", func() { - It("should not watch any dependencies", func() { - session = startGinkgoWithGopath("watch", "-succinct", "-r", "-depth=0") - Eventually(session).Should(gbytes.Say("Identified 3 test suites")) - Eventually(session).Should(gbytes.Say(`A \[0 dependencies\]`)) - Eventually(session).Should(gbytes.Say(`B \[0 dependencies\]`)) - Eventually(session).Should(gbytes.Say(`C \[0 dependencies\]`)) - - modifyCode("A") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("B Suite|C Suite")) - - modifyCode("B") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("B Suite")) - Consistently(session).ShouldNot(gbytes.Say("A Suite|C Suite")) - - modifyCode("C") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("C Suite")) - Consistently(session).ShouldNot(gbytes.Say("A Suite|B Suite")) - }) - }) - - It("should not trigger dependents when tests are changed", func() { - session = startGinkgoWithGopath("watch", "-succinct", "-r", "-depth=2") - Eventually(session).Should(gbytes.Say("Identified 3 test suites")) - Eventually(session).Should(gbytes.Say(`A \[2 dependencies\]`)) - Eventually(session).Should(gbytes.Say(`B \[1 dependency\]`)) - Eventually(session).Should(gbytes.Say(`C \[0 dependencies\]`)) - - modifyTest("A") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("B Suite|C Suite")) - - modifyTest("B") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("B Suite")) - Consistently(session).ShouldNot(gbytes.Say("A Suite|C Suite")) - - modifyTest("C") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("C Suite")) - Consistently(session).ShouldNot(gbytes.Say("A Suite|B Suite")) - }) - }) - - Describe("when new test suite is added", func() { - It("should start monitoring that test suite", func() { - session = startGinkgoWithGopath("watch", "-succinct", "-r") - - Eventually(session).Should(gbytes.Say("Watching 3 suites")) - - pathD := filepath.Join(rootPath, "src", "github.com", "onsi", "D") - - err := os.MkdirAll(pathD, 0700) - Ω(err).ShouldNot(HaveOccurred()) - - copyIn(filepath.Join("watch_fixtures", "D"), pathD) - - Eventually(session).Should(gbytes.Say("Detected 1 new suite")) - Eventually(session).Should(gbytes.Say(`D \[1 dependency\]`)) - Eventually(session).Should(gbytes.Say("D Suite")) - - modifyCode("D") - - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("D Suite")) - - modifyCode("C") - - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("C Suite")) - Eventually(session).Should(gbytes.Say("D Suite")) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location.go deleted file mode 100644 index fa2f0bf..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location.go +++ /dev/null @@ -1,32 +0,0 @@ -package codelocation - -import ( - "regexp" - "runtime" - "runtime/debug" - "strings" - - "github.com/onsi/ginkgo/types" -) - -func New(skip int) types.CodeLocation { - _, file, line, _ := runtime.Caller(skip + 1) - stackTrace := PruneStack(string(debug.Stack()), skip) - return types.CodeLocation{FileName: file, LineNumber: line, FullStackTrace: stackTrace} -} - -func PruneStack(fullStackTrace string, skip int) string { - stack := strings.Split(fullStackTrace, "\n") - if len(stack) > 2*(skip+1) { - stack = stack[2*(skip+1):] - } - prunedStack := []string{} - re := regexp.MustCompile(`\/ginkgo\/|\/pkg\/testing\/|\/pkg\/runtime\/`) - for i := 0; i < len(stack)/2; i++ { - if !re.Match([]byte(stack[i*2])) { - prunedStack = append(prunedStack, stack[i*2]) - prunedStack = append(prunedStack, stack[i*2+1]) - } - } - return strings.Join(prunedStack, "\n") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go deleted file mode 100644 index f06abf3..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package codelocation_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestCodelocation(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "CodeLocation Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go deleted file mode 100644 index 55a9e9d..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package codelocation_test - -import ( - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "runtime" -) - -var _ = Describe("CodeLocation", func() { - var ( - codeLocation types.CodeLocation - expectedFileName string - expectedLineNumber int - ) - - caller0 := func() { - codeLocation = codelocation.New(1) - } - - caller1 := func() { - _, expectedFileName, expectedLineNumber, _ = runtime.Caller(0) - expectedLineNumber += 2 - caller0() - } - - BeforeEach(func() { - caller1() - }) - - It("should use the passed in skip parameter to pick out the correct file & line number", func() { - Ω(codeLocation.FileName).Should(Equal(expectedFileName)) - Ω(codeLocation.LineNumber).Should(Equal(expectedLineNumber)) - }) - - Describe("stringer behavior", func() { - It("should stringify nicely", func() { - Ω(codeLocation.String()).Should(ContainSubstring("code_location_test.go:%d", expectedLineNumber)) - }) - }) - - //There's no better way than to test this private method as it - //goes out of its way to prune out ginkgo related code in the stack trace - Describe("PruneStack", func() { - It("should remove any references to ginkgo and pkg/testing and pkg/runtime", func() { - input := `/Skip/me -Skip: skip() -/Skip/me -Skip: skip() -/Users/whoever/gospace/src/github.com/onsi/ginkgo/whatever.go:10 (0x12314) -Something: Func() -/Users/whoever/gospace/src/github.com/onsi/ginkgo/whatever_else.go:10 (0x12314) -SomethingInternalToGinkgo: Func() -/usr/goroot/pkg/strings/oops.go:10 (0x12341) -Oops: BlowUp() -/Users/whoever/gospace/src/mycode/code.go:10 (0x12341) -MyCode: Func() -/Users/whoever/gospace/src/mycode/code_test.go:10 (0x12341) -MyCodeTest: Func() -/Users/whoever/gospace/src/mycode/code_suite_test.go:12 (0x37f08) -TestFoo: RunSpecs(t, "Foo Suite") -/usr/goroot/pkg/testing/testing.go:12 (0x37f08) -TestingT: Blah() -/usr/goroot/pkg/runtime/runtime.go:12 (0x37f08) -Something: Func() -` - prunedStack := codelocation.PruneStack(input, 1) - Ω(prunedStack).Should(Equal(`/usr/goroot/pkg/strings/oops.go:10 (0x12341) -Oops: BlowUp() -/Users/whoever/gospace/src/mycode/code.go:10 (0x12341) -MyCode: Func() -/Users/whoever/gospace/src/mycode/code_test.go:10 (0x12341) -MyCodeTest: Func() -/Users/whoever/gospace/src/mycode/code_suite_test.go:12 (0x37f08) -TestFoo: RunSpecs(t, "Foo Suite")`)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node.go deleted file mode 100644 index 0737746..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node.go +++ /dev/null @@ -1,151 +0,0 @@ -package containernode - -import ( - "math/rand" - "sort" - - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -type subjectOrContainerNode struct { - containerNode *ContainerNode - subjectNode leafnodes.SubjectNode -} - -func (n subjectOrContainerNode) text() string { - if n.containerNode != nil { - return n.containerNode.Text() - } else { - return n.subjectNode.Text() - } -} - -type CollatedNodes struct { - Containers []*ContainerNode - Subject leafnodes.SubjectNode -} - -type ContainerNode struct { - text string - flag types.FlagType - codeLocation types.CodeLocation - - setupNodes []leafnodes.BasicNode - subjectAndContainerNodes []subjectOrContainerNode -} - -func New(text string, flag types.FlagType, codeLocation types.CodeLocation) *ContainerNode { - return &ContainerNode{ - text: text, - flag: flag, - codeLocation: codeLocation, - } -} - -func (container *ContainerNode) Shuffle(r *rand.Rand) { - sort.Sort(container) - permutation := r.Perm(len(container.subjectAndContainerNodes)) - shuffledNodes := make([]subjectOrContainerNode, len(container.subjectAndContainerNodes)) - for i, j := range permutation { - shuffledNodes[i] = container.subjectAndContainerNodes[j] - } - container.subjectAndContainerNodes = shuffledNodes -} - -func (node *ContainerNode) BackPropagateProgrammaticFocus() bool { - if node.flag == types.FlagTypePending { - return false - } - - shouldUnfocus := false - for _, subjectOrContainerNode := range node.subjectAndContainerNodes { - if subjectOrContainerNode.containerNode != nil { - shouldUnfocus = subjectOrContainerNode.containerNode.BackPropagateProgrammaticFocus() || shouldUnfocus - } else { - shouldUnfocus = (subjectOrContainerNode.subjectNode.Flag() == types.FlagTypeFocused) || shouldUnfocus - } - } - - if shouldUnfocus { - if node.flag == types.FlagTypeFocused { - node.flag = types.FlagTypeNone - } - return true - } - - return node.flag == types.FlagTypeFocused -} - -func (node *ContainerNode) Collate() []CollatedNodes { - return node.collate([]*ContainerNode{}) -} - -func (node *ContainerNode) collate(enclosingContainers []*ContainerNode) []CollatedNodes { - collated := make([]CollatedNodes, 0) - - containers := make([]*ContainerNode, len(enclosingContainers)) - copy(containers, enclosingContainers) - containers = append(containers, node) - - for _, subjectOrContainer := range node.subjectAndContainerNodes { - if subjectOrContainer.containerNode != nil { - collated = append(collated, subjectOrContainer.containerNode.collate(containers)...) - } else { - collated = append(collated, CollatedNodes{ - Containers: containers, - Subject: subjectOrContainer.subjectNode, - }) - } - } - - return collated -} - -func (node *ContainerNode) PushContainerNode(container *ContainerNode) { - node.subjectAndContainerNodes = append(node.subjectAndContainerNodes, subjectOrContainerNode{containerNode: container}) -} - -func (node *ContainerNode) PushSubjectNode(subject leafnodes.SubjectNode) { - node.subjectAndContainerNodes = append(node.subjectAndContainerNodes, subjectOrContainerNode{subjectNode: subject}) -} - -func (node *ContainerNode) PushSetupNode(setupNode leafnodes.BasicNode) { - node.setupNodes = append(node.setupNodes, setupNode) -} - -func (node *ContainerNode) SetupNodesOfType(nodeType types.SpecComponentType) []leafnodes.BasicNode { - nodes := []leafnodes.BasicNode{} - for _, setupNode := range node.setupNodes { - if setupNode.Type() == nodeType { - nodes = append(nodes, setupNode) - } - } - return nodes -} - -func (node *ContainerNode) Text() string { - return node.text -} - -func (node *ContainerNode) CodeLocation() types.CodeLocation { - return node.codeLocation -} - -func (node *ContainerNode) Flag() types.FlagType { - return node.flag -} - -//sort.Interface - -func (node *ContainerNode) Len() int { - return len(node.subjectAndContainerNodes) -} - -func (node *ContainerNode) Less(i, j int) bool { - return node.subjectAndContainerNodes[i].text() < node.subjectAndContainerNodes[j].text() -} - -func (node *ContainerNode) Swap(i, j int) { - node.subjectAndContainerNodes[i], node.subjectAndContainerNodes[j] = node.subjectAndContainerNodes[j], node.subjectAndContainerNodes[i] -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go deleted file mode 100644 index c6fc314..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package containernode_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestContainernode(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Containernode Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_test.go deleted file mode 100644 index b8d61b1..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package containernode_test - -import ( - "github.com/onsi/ginkgo/internal/leafnodes" - "math/rand" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - . "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Container Node", func() { - var ( - codeLocation types.CodeLocation - container *ContainerNode - ) - - BeforeEach(func() { - codeLocation = codelocation.New(0) - container = New("description text", types.FlagTypeFocused, codeLocation) - }) - - Describe("creating a container node", func() { - It("can answer questions about itself", func() { - Ω(container.Text()).Should(Equal("description text")) - Ω(container.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(container.CodeLocation()).Should(Equal(codeLocation)) - }) - }) - - Describe("pushing setup nodes", func() { - It("can append setup nodes of various types and fetch them by type", func() { - befA := leafnodes.NewBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - befB := leafnodes.NewBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - aftA := leafnodes.NewAfterEachNode(func() {}, codelocation.New(0), 0, nil, 0) - aftB := leafnodes.NewAfterEachNode(func() {}, codelocation.New(0), 0, nil, 0) - jusBefA := leafnodes.NewJustBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - jusBefB := leafnodes.NewJustBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - - container.PushSetupNode(befA) - container.PushSetupNode(befB) - container.PushSetupNode(aftA) - container.PushSetupNode(aftB) - container.PushSetupNode(jusBefA) - container.PushSetupNode(jusBefB) - - subject := leafnodes.NewItNode("subject", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(subject) - - Ω(container.SetupNodesOfType(types.SpecComponentTypeBeforeEach)).Should(Equal([]leafnodes.BasicNode{befA, befB})) - Ω(container.SetupNodesOfType(types.SpecComponentTypeAfterEach)).Should(Equal([]leafnodes.BasicNode{aftA, aftB})) - Ω(container.SetupNodesOfType(types.SpecComponentTypeJustBeforeEach)).Should(Equal([]leafnodes.BasicNode{jusBefA, jusBefB})) - Ω(container.SetupNodesOfType(types.SpecComponentTypeIt)).Should(BeEmpty()) //subjects are not setup nodes - }) - }) - - Context("With appended containers and subject nodes", func() { - var ( - itA, itB, innerItA, innerItB leafnodes.SubjectNode - innerContainer *ContainerNode - ) - - BeforeEach(func() { - itA = leafnodes.NewItNode("Banana", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - itB = leafnodes.NewItNode("Apple", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - innerItB = leafnodes.NewItNode("inner B", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - - innerContainer = New("Orange", types.FlagTypeNone, codelocation.New(0)) - - container.PushSubjectNode(itA) - container.PushContainerNode(innerContainer) - innerContainer.PushSubjectNode(innerItA) - innerContainer.PushSubjectNode(innerItB) - container.PushSubjectNode(itB) - }) - - Describe("Collating", func() { - It("should return a collated set of containers and subject nodes in the correct order", func() { - collated := container.Collate() - Ω(collated).Should(HaveLen(4)) - - Ω(collated[0]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container}, - Subject: itA, - })) - - Ω(collated[1]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container, innerContainer}, - Subject: innerItA, - })) - - Ω(collated[2]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container, innerContainer}, - Subject: innerItB, - })) - - Ω(collated[3]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container}, - Subject: itB, - })) - }) - }) - - Describe("Backpropagating Programmatic Focus", func() { - //This allows inner focused specs to override the focus of outer focussed - //specs and more closely maps to what a developer wants to happen - //when debugging a test suite - - Context("when a parent is focused *and* an inner subject is focused", func() { - BeforeEach(func() { - container = New("description text", types.FlagTypeFocused, codeLocation) - itA = leafnodes.NewItNode("A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(itA) - - innerContainer = New("Orange", types.FlagTypeNone, codelocation.New(0)) - container.PushContainerNode(innerContainer) - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeFocused, codelocation.New(0), 0, nil, 0) - innerContainer.PushSubjectNode(innerItA) - }) - - It("should unfocus the parent", func() { - container.BackPropagateProgrammaticFocus() - - Ω(container.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(itA.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerContainer.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerItA.Flag()).Should(Equal(types.FlagTypeFocused)) - }) - }) - - Context("when a parent is focused *and* an inner container is focused", func() { - BeforeEach(func() { - container = New("description text", types.FlagTypeFocused, codeLocation) - itA = leafnodes.NewItNode("A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(itA) - - innerContainer = New("Orange", types.FlagTypeFocused, codelocation.New(0)) - container.PushContainerNode(innerContainer) - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - innerContainer.PushSubjectNode(innerItA) - }) - - It("should unfocus the parent", func() { - container.BackPropagateProgrammaticFocus() - - Ω(container.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(itA.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerContainer.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(innerItA.Flag()).Should(Equal(types.FlagTypeNone)) - }) - }) - - Context("when a parent is pending and a child is focused", func() { - BeforeEach(func() { - container = New("description text", types.FlagTypeFocused, codeLocation) - itA = leafnodes.NewItNode("A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(itA) - - innerContainer = New("Orange", types.FlagTypePending, codelocation.New(0)) - container.PushContainerNode(innerContainer) - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeFocused, codelocation.New(0), 0, nil, 0) - innerContainer.PushSubjectNode(innerItA) - }) - - It("should not do anything", func() { - container.BackPropagateProgrammaticFocus() - - Ω(container.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(itA.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerContainer.Flag()).Should(Equal(types.FlagTypePending)) - Ω(innerItA.Flag()).Should(Equal(types.FlagTypeFocused)) - }) - }) - }) - - Describe("Shuffling", func() { - var unshuffledCollation []CollatedNodes - BeforeEach(func() { - unshuffledCollation = container.Collate() - - r := rand.New(rand.NewSource(17)) - container.Shuffle(r) - }) - - It("should sort, and then shuffle, the top level contents of the container", func() { - shuffledCollation := container.Collate() - Ω(shuffledCollation).Should(HaveLen(len(unshuffledCollation))) - Ω(shuffledCollation).ShouldNot(Equal(unshuffledCollation)) - - for _, entry := range unshuffledCollation { - Ω(shuffledCollation).Should(ContainElement(entry)) - } - - innerAIndex, innerBIndex := 0, 0 - for i, entry := range shuffledCollation { - if entry.Subject == innerItA { - innerAIndex = i - } else if entry.Subject == innerItB { - innerBIndex = i - } - } - - Ω(innerAIndex).Should(Equal(innerBIndex - 1)) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer.go deleted file mode 100644 index 4019666..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer.go +++ /dev/null @@ -1,79 +0,0 @@ -package failer - -import ( - "fmt" - "sync" - - "github.com/onsi/ginkgo/types" -) - -type Failer struct { - lock *sync.Mutex - failure types.SpecFailure - state types.SpecState -} - -func New() *Failer { - return &Failer{ - lock: &sync.Mutex{}, - state: types.SpecStatePassed, - } -} - -func (f *Failer) Panic(location types.CodeLocation, forwardedPanic interface{}) { - f.lock.Lock() - defer f.lock.Unlock() - - if f.state == types.SpecStatePassed { - f.state = types.SpecStatePanicked - f.failure = types.SpecFailure{ - Message: "Test Panicked", - Location: location, - ForwardedPanic: fmt.Sprintf("%v", forwardedPanic), - } - } -} - -func (f *Failer) Timeout(location types.CodeLocation) { - f.lock.Lock() - defer f.lock.Unlock() - - if f.state == types.SpecStatePassed { - f.state = types.SpecStateTimedOut - f.failure = types.SpecFailure{ - Message: "Timed out", - Location: location, - } - } -} - -func (f *Failer) Fail(message string, location types.CodeLocation) { - f.lock.Lock() - defer f.lock.Unlock() - - if f.state == types.SpecStatePassed { - f.state = types.SpecStateFailed - f.failure = types.SpecFailure{ - Message: message, - Location: location, - } - } -} - -func (f *Failer) Drain(componentType types.SpecComponentType, componentIndex int, componentCodeLocation types.CodeLocation) (types.SpecFailure, types.SpecState) { - f.lock.Lock() - defer f.lock.Unlock() - - failure := f.failure - outcome := f.state - if outcome != types.SpecStatePassed { - failure.ComponentType = componentType - failure.ComponentIndex = componentIndex - failure.ComponentCodeLocation = componentCodeLocation - } - - f.state = types.SpecStatePassed - f.failure = types.SpecFailure{} - - return failure, outcome -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go deleted file mode 100644 index 8dce7be..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package failer_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestFailer(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Failer Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_test.go deleted file mode 100644 index 3da62db..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package failer_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/failer" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Failer", func() { - var ( - failer *Failer - codeLocationA types.CodeLocation - codeLocationB types.CodeLocation - ) - - BeforeEach(func() { - codeLocationA = codelocation.New(0) - codeLocationB = codelocation.New(0) - failer = New() - }) - - Context("with no failures", func() { - It("should return success when drained", func() { - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(BeZero()) - Ω(state).Should(Equal(types.SpecStatePassed)) - }) - }) - - Describe("Fail", func() { - It("should handle failures", func() { - failer.Fail("something failed", codeLocationA) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "something failed", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateFailed)) - }) - }) - - Describe("Panic", func() { - It("should handle panics", func() { - failer.Panic(codeLocationA, "some forwarded panic") - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "Test Panicked", - Location: codeLocationA, - ForwardedPanic: "some forwarded panic", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStatePanicked)) - }) - }) - - Describe("Timeout", func() { - It("should handle timeouts", func() { - failer.Timeout(codeLocationA) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "Timed out", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateTimedOut)) - }) - }) - - Context("when multiple failures are registered", func() { - BeforeEach(func() { - failer.Fail("something failed", codeLocationA) - failer.Fail("something else failed", codeLocationA) - }) - - It("should only report the first one when drained", func() { - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "something failed", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateFailed)) - }) - - It("should report subsequent failures after being drained", func() { - failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - failer.Fail("yet another thing failed", codeLocationA) - - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "yet another thing failed", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateFailed)) - }) - - It("should report sucess on subsequent drains if no errors occur", func() { - failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(BeZero()) - Ω(state).Should(Equal(types.SpecStatePassed)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go deleted file mode 100644 index bc0dd1a..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go +++ /dev/null @@ -1,95 +0,0 @@ -package leafnodes - -import ( - "math" - "time" - - "sync" - - "github.com/onsi/ginkgo/types" -) - -type benchmarker struct { - mu sync.Mutex - measurements map[string]*types.SpecMeasurement - orderCounter int -} - -func newBenchmarker() *benchmarker { - return &benchmarker{ - measurements: make(map[string]*types.SpecMeasurement, 0), - } -} - -func (b *benchmarker) Time(name string, body func(), info ...interface{}) (elapsedTime time.Duration) { - t := time.Now() - body() - elapsedTime = time.Since(t) - - b.mu.Lock() - defer b.mu.Unlock() - measurement := b.getMeasurement(name, "Fastest Time", "Slowest Time", "Average Time", "s", info...) - measurement.Results = append(measurement.Results, elapsedTime.Seconds()) - - return -} - -func (b *benchmarker) RecordValue(name string, value float64, info ...interface{}) { - measurement := b.getMeasurement(name, "Smallest", " Largest", " Average", "", info...) - b.mu.Lock() - defer b.mu.Unlock() - measurement.Results = append(measurement.Results, value) -} - -func (b *benchmarker) getMeasurement(name string, smallestLabel string, largestLabel string, averageLabel string, units string, info ...interface{}) *types.SpecMeasurement { - measurement, ok := b.measurements[name] - if !ok { - var computedInfo interface{} - computedInfo = nil - if len(info) > 0 { - computedInfo = info[0] - } - measurement = &types.SpecMeasurement{ - Name: name, - Info: computedInfo, - Order: b.orderCounter, - SmallestLabel: smallestLabel, - LargestLabel: largestLabel, - AverageLabel: averageLabel, - Units: units, - Results: make([]float64, 0), - } - b.measurements[name] = measurement - b.orderCounter++ - } - - return measurement -} - -func (b *benchmarker) measurementsReport() map[string]*types.SpecMeasurement { - b.mu.Lock() - defer b.mu.Unlock() - for _, measurement := range b.measurements { - measurement.Smallest = math.MaxFloat64 - measurement.Largest = -math.MaxFloat64 - sum := float64(0) - sumOfSquares := float64(0) - - for _, result := range measurement.Results { - if result > measurement.Largest { - measurement.Largest = result - } - if result < measurement.Smallest { - measurement.Smallest = result - } - sum += result - sumOfSquares += result * result - } - - n := float64(len(measurement.Results)) - measurement.Average = sum / n - measurement.StdDeviation = math.Sqrt(sumOfSquares/n - (sum/n)*(sum/n)) - } - - return b.measurements -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/interfaces.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/interfaces.go deleted file mode 100644 index 8c3902d..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/interfaces.go +++ /dev/null @@ -1,19 +0,0 @@ -package leafnodes - -import ( - "github.com/onsi/ginkgo/types" -) - -type BasicNode interface { - Type() types.SpecComponentType - Run() (types.SpecState, types.SpecFailure) - CodeLocation() types.CodeLocation -} - -type SubjectNode interface { - BasicNode - - Text() string - Flag() types.FlagType - Samples() int -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/it_node.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/it_node.go deleted file mode 100644 index c76fe3a..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/it_node.go +++ /dev/null @@ -1,46 +0,0 @@ -package leafnodes - -import ( - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -type ItNode struct { - runner *runner - - flag types.FlagType - text string -} - -func NewItNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *ItNode { - return &ItNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeIt, componentIndex), - flag: flag, - text: text, - } -} - -func (node *ItNode) Run() (outcome types.SpecState, failure types.SpecFailure) { - return node.runner.run() -} - -func (node *ItNode) Type() types.SpecComponentType { - return types.SpecComponentTypeIt -} - -func (node *ItNode) Text() string { - return node.text -} - -func (node *ItNode) Flag() types.FlagType { - return node.flag -} - -func (node *ItNode) CodeLocation() types.CodeLocation { - return node.runner.codeLocation -} - -func (node *ItNode) Samples() int { - return 1 -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go deleted file mode 100644 index 29fa0c6..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("It Nodes", func() { - It("should report the correct type, text, flag, and code location", func() { - codeLocation := codelocation.New(0) - it := NewItNode("my it node", func() {}, types.FlagTypeFocused, codeLocation, 0, nil, 3) - Ω(it.Type()).Should(Equal(types.SpecComponentTypeIt)) - Ω(it.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(it.Text()).Should(Equal("my it node")) - Ω(it.CodeLocation()).Should(Equal(codeLocation)) - Ω(it.Samples()).Should(Equal(1)) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go deleted file mode 100644 index a7ba9e0..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestLeafNode(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "LeafNode Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go deleted file mode 100644 index efc3348..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go +++ /dev/null @@ -1,61 +0,0 @@ -package leafnodes - -import ( - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "reflect" -) - -type MeasureNode struct { - runner *runner - - text string - flag types.FlagType - samples int - benchmarker *benchmarker -} - -func NewMeasureNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, samples int, failer *failer.Failer, componentIndex int) *MeasureNode { - benchmarker := newBenchmarker() - - wrappedBody := func() { - reflect.ValueOf(body).Call([]reflect.Value{reflect.ValueOf(benchmarker)}) - } - - return &MeasureNode{ - runner: newRunner(wrappedBody, codeLocation, 0, failer, types.SpecComponentTypeMeasure, componentIndex), - - text: text, - flag: flag, - samples: samples, - benchmarker: benchmarker, - } -} - -func (node *MeasureNode) Run() (outcome types.SpecState, failure types.SpecFailure) { - return node.runner.run() -} - -func (node *MeasureNode) MeasurementsReport() map[string]*types.SpecMeasurement { - return node.benchmarker.measurementsReport() -} - -func (node *MeasureNode) Type() types.SpecComponentType { - return types.SpecComponentTypeMeasure -} - -func (node *MeasureNode) Text() string { - return node.text -} - -func (node *MeasureNode) Flag() types.FlagType { - return node.flag -} - -func (node *MeasureNode) CodeLocation() types.CodeLocation { - return node.runner.codeLocation -} - -func (node *MeasureNode) Samples() int { - return node.samples -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go deleted file mode 100644 index 4dcd00b..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -var _ = Describe("Measure Nodes", func() { - It("should report the correct type, text, flag, and code location", func() { - codeLocation := codelocation.New(0) - measure := NewMeasureNode("my measure node", func(b Benchmarker) {}, types.FlagTypeFocused, codeLocation, 10, nil, 3) - Ω(measure.Type()).Should(Equal(types.SpecComponentTypeMeasure)) - Ω(measure.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(measure.Text()).Should(Equal("my measure node")) - Ω(measure.CodeLocation()).Should(Equal(codeLocation)) - Ω(measure.Samples()).Should(Equal(10)) - }) - - Describe("benchmarking", func() { - var measure *MeasureNode - - Describe("Value", func() { - BeforeEach(func() { - measure = NewMeasureNode("the measurement", func(b Benchmarker) { - b.RecordValue("foo", 7, "info!") - b.RecordValue("foo", 2) - b.RecordValue("foo", 3) - b.RecordValue("bar", 0.3) - b.RecordValue("bar", 0.1) - b.RecordValue("bar", 0.5) - b.RecordValue("bar", 0.7) - }, types.FlagTypeFocused, codelocation.New(0), 1, Failer.New(), 3) - Ω(measure.Run()).Should(Equal(types.SpecStatePassed)) - }) - - It("records passed in values and reports on them", func() { - report := measure.MeasurementsReport() - Ω(report).Should(HaveLen(2)) - Ω(report["foo"].Name).Should(Equal("foo")) - Ω(report["foo"].Info).Should(Equal("info!")) - Ω(report["foo"].Order).Should(Equal(0)) - Ω(report["foo"].SmallestLabel).Should(Equal("Smallest")) - Ω(report["foo"].LargestLabel).Should(Equal(" Largest")) - Ω(report["foo"].AverageLabel).Should(Equal(" Average")) - Ω(report["foo"].Units).Should(Equal("")) - Ω(report["foo"].Results).Should(Equal([]float64{7, 2, 3})) - Ω(report["foo"].Smallest).Should(BeNumerically("==", 2)) - Ω(report["foo"].Largest).Should(BeNumerically("==", 7)) - Ω(report["foo"].Average).Should(BeNumerically("==", 4)) - Ω(report["foo"].StdDeviation).Should(BeNumerically("~", 2.16, 0.01)) - - Ω(report["bar"].Name).Should(Equal("bar")) - Ω(report["bar"].Info).Should(BeNil()) - Ω(report["bar"].SmallestLabel).Should(Equal("Smallest")) - Ω(report["bar"].Order).Should(Equal(1)) - Ω(report["bar"].LargestLabel).Should(Equal(" Largest")) - Ω(report["bar"].AverageLabel).Should(Equal(" Average")) - Ω(report["bar"].Units).Should(Equal("")) - Ω(report["bar"].Results).Should(Equal([]float64{0.3, 0.1, 0.5, 0.7})) - Ω(report["bar"].Smallest).Should(BeNumerically("==", 0.1)) - Ω(report["bar"].Largest).Should(BeNumerically("==", 0.7)) - Ω(report["bar"].Average).Should(BeNumerically("==", 0.4)) - Ω(report["bar"].StdDeviation).Should(BeNumerically("~", 0.22, 0.01)) - }) - }) - - Describe("Time", func() { - BeforeEach(func() { - measure = NewMeasureNode("the measurement", func(b Benchmarker) { - b.Time("foo", func() { - time.Sleep(100 * time.Millisecond) - }, "info!") - b.Time("foo", func() { - time.Sleep(200 * time.Millisecond) - }) - b.Time("foo", func() { - time.Sleep(170 * time.Millisecond) - }) - }, types.FlagTypeFocused, codelocation.New(0), 1, Failer.New(), 3) - Ω(measure.Run()).Should(Equal(types.SpecStatePassed)) - }) - - It("records passed in values and reports on them", func() { - report := measure.MeasurementsReport() - Ω(report).Should(HaveLen(1)) - Ω(report["foo"].Name).Should(Equal("foo")) - Ω(report["foo"].Info).Should(Equal("info!")) - Ω(report["foo"].SmallestLabel).Should(Equal("Fastest Time")) - Ω(report["foo"].LargestLabel).Should(Equal("Slowest Time")) - Ω(report["foo"].AverageLabel).Should(Equal("Average Time")) - Ω(report["foo"].Units).Should(Equal("s")) - Ω(report["foo"].Results).Should(HaveLen(3)) - Ω(report["foo"].Results[0]).Should(BeNumerically("~", 0.1, 0.01)) - Ω(report["foo"].Results[1]).Should(BeNumerically("~", 0.2, 0.01)) - Ω(report["foo"].Results[2]).Should(BeNumerically("~", 0.17, 0.01)) - Ω(report["foo"].Smallest).Should(BeNumerically("~", 0.1, 0.01)) - Ω(report["foo"].Largest).Should(BeNumerically("~", 0.2, 0.01)) - Ω(report["foo"].Average).Should(BeNumerically("~", 0.16, 0.01)) - Ω(report["foo"].StdDeviation).Should(BeNumerically("~", 0.04, 0.01)) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/runner.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/runner.go deleted file mode 100644 index 04ec6db..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/runner.go +++ /dev/null @@ -1,107 +0,0 @@ -package leafnodes - -import ( - "fmt" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "reflect" - "time" -) - -type runner struct { - isAsync bool - asyncFunc func(chan<- interface{}) - syncFunc func() - codeLocation types.CodeLocation - timeoutThreshold time.Duration - nodeType types.SpecComponentType - componentIndex int - failer *failer.Failer -} - -func newRunner(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, nodeType types.SpecComponentType, componentIndex int) *runner { - bodyType := reflect.TypeOf(body) - if bodyType.Kind() != reflect.Func { - panic(fmt.Sprintf("Expected a function but got something else at %v", codeLocation)) - } - - runner := &runner{ - codeLocation: codeLocation, - timeoutThreshold: timeout, - failer: failer, - nodeType: nodeType, - componentIndex: componentIndex, - } - - switch bodyType.NumIn() { - case 0: - runner.syncFunc = body.(func()) - return runner - case 1: - if !(bodyType.In(0).Kind() == reflect.Chan && bodyType.In(0).Elem().Kind() == reflect.Interface) { - panic(fmt.Sprintf("Must pass a Done channel to function at %v", codeLocation)) - } - - wrappedBody := func(done chan<- interface{}) { - bodyValue := reflect.ValueOf(body) - bodyValue.Call([]reflect.Value{reflect.ValueOf(done)}) - } - - runner.isAsync = true - runner.asyncFunc = wrappedBody - return runner - } - - panic(fmt.Sprintf("Too many arguments to function at %v", codeLocation)) -} - -func (r *runner) run() (outcome types.SpecState, failure types.SpecFailure) { - if r.isAsync { - return r.runAsync() - } else { - return r.runSync() - } -} - -func (r *runner) runAsync() (outcome types.SpecState, failure types.SpecFailure) { - done := make(chan interface{}, 1) - - go func() { - defer func() { - if e := recover(); e != nil { - r.failer.Panic(codelocation.New(2), e) - select { - case <-done: - break - default: - close(done) - } - } - }() - - r.asyncFunc(done) - }() - - select { - case <-done: - case <-time.After(r.timeoutThreshold): - r.failer.Timeout(r.codeLocation) - } - - failure, outcome = r.failer.Drain(r.nodeType, r.componentIndex, r.codeLocation) - return -} -func (r *runner) runSync() (outcome types.SpecState, failure types.SpecFailure) { - defer func() { - if e := recover(); e != nil { - r.failer.Panic(codelocation.New(2), e) - } - - failure, outcome = r.failer.Drain(r.nodeType, r.componentIndex, r.codeLocation) - }() - - r.syncFunc() - - return -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go deleted file mode 100644 index 6b725a6..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go +++ /dev/null @@ -1,41 +0,0 @@ -package leafnodes - -import ( - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -type SetupNode struct { - runner *runner -} - -func (node *SetupNode) Run() (outcome types.SpecState, failure types.SpecFailure) { - return node.runner.run() -} - -func (node *SetupNode) Type() types.SpecComponentType { - return node.runner.nodeType -} - -func (node *SetupNode) CodeLocation() types.CodeLocation { - return node.runner.codeLocation -} - -func NewBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { - return &SetupNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeBeforeEach, componentIndex), - } -} - -func NewAfterEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { - return &SetupNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeAfterEach, componentIndex), - } -} - -func NewJustBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { - return &SetupNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeJustBeforeEach, componentIndex), - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go deleted file mode 100644 index d5b9251..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - - . "github.com/onsi/ginkgo/internal/leafnodes" - - "github.com/onsi/ginkgo/internal/codelocation" -) - -var _ = Describe("Setup Nodes", func() { - Describe("BeforeEachNodes", func() { - It("should report the correct type and code location", func() { - codeLocation := codelocation.New(0) - beforeEach := NewBeforeEachNode(func() {}, codeLocation, 0, nil, 3) - Ω(beforeEach.Type()).Should(Equal(types.SpecComponentTypeBeforeEach)) - Ω(beforeEach.CodeLocation()).Should(Equal(codeLocation)) - }) - }) - - Describe("AfterEachNodes", func() { - It("should report the correct type and code location", func() { - codeLocation := codelocation.New(0) - afterEach := NewAfterEachNode(func() {}, codeLocation, 0, nil, 3) - Ω(afterEach.Type()).Should(Equal(types.SpecComponentTypeAfterEach)) - Ω(afterEach.CodeLocation()).Should(Equal(codeLocation)) - }) - }) - - Describe("JustBeforeEachNodes", func() { - It("should report the correct type and code location", func() { - codeLocation := codelocation.New(0) - justBeforeEach := NewJustBeforeEachNode(func() {}, codeLocation, 0, nil, 3) - Ω(justBeforeEach.Type()).Should(Equal(types.SpecComponentTypeJustBeforeEach)) - Ω(justBeforeEach.CodeLocation()).Should(Equal(codeLocation)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go deleted file mode 100644 index 9007d1b..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go +++ /dev/null @@ -1,326 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "reflect" - "runtime" - "time" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -type runnable interface { - Run() (outcome types.SpecState, failure types.SpecFailure) - CodeLocation() types.CodeLocation -} - -func SynchronousSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType, componentIndex int) { - var ( - outcome types.SpecState - failure types.SpecFailure - - failer *Failer.Failer - - componentCodeLocation types.CodeLocation - innerCodeLocation types.CodeLocation - - didRun bool - ) - - BeforeEach(func() { - failer = Failer.New() - componentCodeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - - didRun = false - }) - - Describe("synchronous functions", func() { - Context("when the function passes", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - }, 0, failer, componentCodeLocation).Run() - }) - - It("should have a succesful outcome", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePassed)) - Ω(failure).Should(BeZero()) - }) - }) - - Context("when a failure occurs", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - failer.Fail("bam", innerCodeLocation) - panic("should not matter") - }, 0, failer, componentCodeLocation).Run() - }) - - It("should return the failure", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStateFailed)) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "bam", - Location: innerCodeLocation, - ForwardedPanic: "", - ComponentIndex: componentIndex, - ComponentType: componentType, - ComponentCodeLocation: componentCodeLocation, - })) - }) - }) - - Context("when a panic occurs", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - innerCodeLocation = codelocation.New(0) - panic("ack!") - }, 0, failer, componentCodeLocation).Run() - }) - - It("should return the panic", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePanicked)) - Ω(failure.ForwardedPanic).Should(Equal("ack!")) - }) - }) - }) -} - -func AsynchronousSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType, componentIndex int) { - var ( - outcome types.SpecState - failure types.SpecFailure - - failer *Failer.Failer - - componentCodeLocation types.CodeLocation - innerCodeLocation types.CodeLocation - - didRun bool - ) - - BeforeEach(func() { - failer = Failer.New() - componentCodeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - - didRun = false - }) - - Describe("asynchronous functions", func() { - var timeoutDuration time.Duration - - BeforeEach(func() { - timeoutDuration = time.Duration(1 * float64(time.Second)) - }) - - Context("when running", func() { - It("should run the function as a goroutine, and block until it's done", func() { - initialNumberOfGoRoutines := runtime.NumGoroutine() - numberOfGoRoutines := 0 - - build(func(done Done) { - didRun = true - numberOfGoRoutines = runtime.NumGoroutine() - close(done) - }, timeoutDuration, failer, componentCodeLocation).Run() - - Ω(didRun).Should(BeTrue()) - Ω(numberOfGoRoutines).Should(BeNumerically(">=", initialNumberOfGoRoutines+1)) - }) - }) - - Context("when the function passes", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - close(done) - }, timeoutDuration, failer, componentCodeLocation).Run() - }) - - It("should have a succesful outcome", func() { - Ω(didRun).Should(BeTrue()) - Ω(outcome).Should(Equal(types.SpecStatePassed)) - Ω(failure).Should(BeZero()) - }) - }) - - Context("when the function fails", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - failer.Fail("bam", innerCodeLocation) - time.Sleep(20 * time.Millisecond) - panic("doesn't matter") - close(done) - }, 10*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the failure", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStateFailed)) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "bam", - Location: innerCodeLocation, - ForwardedPanic: "", - ComponentIndex: componentIndex, - ComponentType: componentType, - ComponentCodeLocation: componentCodeLocation, - })) - }) - }) - - Context("when the function times out", func() { - var guard chan struct{} - - BeforeEach(func() { - guard = make(chan struct{}) - outcome, failure = build(func(done Done) { - didRun = true - time.Sleep(20 * time.Millisecond) - close(guard) - panic("doesn't matter") - close(done) - }, 10*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the timeout", func() { - <-guard - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStateTimedOut)) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "Timed out", - Location: componentCodeLocation, - ForwardedPanic: "", - ComponentIndex: componentIndex, - ComponentType: componentType, - ComponentCodeLocation: componentCodeLocation, - })) - }) - }) - - Context("when the function panics", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - innerCodeLocation = codelocation.New(0) - panic("ack!") - }, 100*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the panic", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePanicked)) - Ω(failure.ForwardedPanic).Should(Equal("ack!")) - }) - }) - }) -} - -func InvalidSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType) { - var ( - failer *Failer.Failer - componentCodeLocation types.CodeLocation - innerCodeLocation types.CodeLocation - ) - - BeforeEach(func() { - failer = Failer.New() - componentCodeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - }) - - Describe("invalid functions", func() { - Context("when passed something that's not a function", func() { - It("should panic", func() { - Ω(func() { - build("not a function", 0, failer, componentCodeLocation) - }).Should(Panic()) - }) - }) - - Context("when the function takes the wrong kind of argument", func() { - It("should panic", func() { - Ω(func() { - build(func(oops string) {}, 0, failer, componentCodeLocation) - }).Should(Panic()) - }) - }) - - Context("when the function takes more than one argument", func() { - It("should panic", func() { - Ω(func() { - build(func(done Done, oops string) {}, 0, failer, componentCodeLocation) - }).Should(Panic()) - }) - }) - }) -} - -var _ = Describe("Shared RunnableNode behavior", func() { - Describe("It Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewItNode("", body, types.FlagTypeFocused, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeIt, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeIt, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeIt) - }) - - Describe("Measure Nodes", func() { - build := func(body interface{}, _ time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewMeasureNode("", func(Benchmarker) { - reflect.ValueOf(body).Call([]reflect.Value{}) - }, types.FlagTypeFocused, componentCodeLocation, 10, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeMeasure, 3) - }) - - Describe("BeforeEach Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewBeforeEachNode(body, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach) - }) - - Describe("AfterEach Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewAfterEachNode(body, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach) - }) - - Describe("JustBeforeEach Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewJustBeforeEachNode(body, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go deleted file mode 100644 index 2ccc7dc..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go +++ /dev/null @@ -1,54 +0,0 @@ -package leafnodes - -import ( - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -type SuiteNode interface { - Run(parallelNode int, parallelTotal int, syncHost string) bool - Passed() bool - Summary() *types.SetupSummary -} - -type simpleSuiteNode struct { - runner *runner - outcome types.SpecState - failure types.SpecFailure - runTime time.Duration -} - -func (node *simpleSuiteNode) Run(parallelNode int, parallelTotal int, syncHost string) bool { - t := time.Now() - node.outcome, node.failure = node.runner.run() - node.runTime = time.Since(t) - - return node.outcome == types.SpecStatePassed -} - -func (node *simpleSuiteNode) Passed() bool { - return node.outcome == types.SpecStatePassed -} - -func (node *simpleSuiteNode) Summary() *types.SetupSummary { - return &types.SetupSummary{ - ComponentType: node.runner.nodeType, - CodeLocation: node.runner.codeLocation, - State: node.outcome, - RunTime: node.runTime, - Failure: node.failure, - } -} - -func NewBeforeSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer) SuiteNode { - return &simpleSuiteNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeBeforeSuite, 0), - } -} - -func NewAfterSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer) SuiteNode { - return &simpleSuiteNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeAfterSuite, 0), - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go deleted file mode 100644 index 246b329..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go +++ /dev/null @@ -1,230 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - . "github.com/onsi/ginkgo/internal/leafnodes" - - "time" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("SuiteNodes", func() { - Describe("BeforeSuite nodes", func() { - var befSuite SuiteNode - var failer *Failer.Failer - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - - BeforeEach(func() { - failer = Failer.New() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - }) - - Context("when the body passes", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func() { - time.Sleep(10 * time.Millisecond) - }, codeLocation, 0, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return true when run and report as passed", func() { - Ω(outcome).Should(BeTrue()) - Ω(befSuite.Passed()).Should(BeTrue()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.CodeLocation).Should(Equal(codeLocation)) - Ω(summary.State).Should(Equal(types.SpecStatePassed)) - Ω(summary.RunTime).Should(BeNumerically(">=", 10*time.Millisecond)) - Ω(summary.Failure).Should(BeZero()) - }) - }) - - Context("when the body fails", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func() { - failer.Fail("oops", innerCodeLocation) - }, codeLocation, 0, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(befSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("oops")) - Ω(summary.Failure.Location).Should(Equal(innerCodeLocation)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body times out", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func(done Done) { - }, codeLocation, time.Millisecond, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(befSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateTimedOut)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body panics", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func() { - panic("bam") - }, codeLocation, 0, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(befSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStatePanicked)) - Ω(summary.Failure.ForwardedPanic).Should(Equal("bam")) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - }) - - Describe("AfterSuite nodes", func() { - var aftSuite SuiteNode - var failer *Failer.Failer - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - - BeforeEach(func() { - failer = Failer.New() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - }) - - Context("when the body passes", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func() { - time.Sleep(10 * time.Millisecond) - }, codeLocation, 0, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return true when run and report as passed", func() { - Ω(outcome).Should(BeTrue()) - Ω(aftSuite.Passed()).Should(BeTrue()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.CodeLocation).Should(Equal(codeLocation)) - Ω(summary.State).Should(Equal(types.SpecStatePassed)) - Ω(summary.RunTime).Should(BeNumerically(">=", 10*time.Millisecond)) - Ω(summary.Failure).Should(BeZero()) - }) - }) - - Context("when the body fails", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func() { - failer.Fail("oops", innerCodeLocation) - }, codeLocation, 0, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(aftSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("oops")) - Ω(summary.Failure.Location).Should(Equal(innerCodeLocation)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body times out", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func(done Done) { - }, codeLocation, time.Millisecond, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(aftSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateTimedOut)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body panics", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func() { - panic("bam") - }, codeLocation, 0, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(aftSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStatePanicked)) - Ω(summary.Failure.ForwardedPanic).Should(Equal("bam")) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go deleted file mode 100644 index e7030d9..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go +++ /dev/null @@ -1,89 +0,0 @@ -package leafnodes - -import ( - "encoding/json" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "io/ioutil" - "net/http" - "time" -) - -type synchronizedAfterSuiteNode struct { - runnerA *runner - runnerB *runner - - outcome types.SpecState - failure types.SpecFailure - runTime time.Duration -} - -func NewSynchronizedAfterSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer) SuiteNode { - return &synchronizedAfterSuiteNode{ - runnerA: newRunner(bodyA, codeLocation, timeout, failer, types.SpecComponentTypeAfterSuite, 0), - runnerB: newRunner(bodyB, codeLocation, timeout, failer, types.SpecComponentTypeAfterSuite, 0), - } -} - -func (node *synchronizedAfterSuiteNode) Run(parallelNode int, parallelTotal int, syncHost string) bool { - node.outcome, node.failure = node.runnerA.run() - - if parallelNode == 1 { - if parallelTotal > 1 { - node.waitUntilOtherNodesAreDone(syncHost) - } - - outcome, failure := node.runnerB.run() - - if node.outcome == types.SpecStatePassed { - node.outcome, node.failure = outcome, failure - } - } - - return node.outcome == types.SpecStatePassed -} - -func (node *synchronizedAfterSuiteNode) Passed() bool { - return node.outcome == types.SpecStatePassed -} - -func (node *synchronizedAfterSuiteNode) Summary() *types.SetupSummary { - return &types.SetupSummary{ - ComponentType: node.runnerA.nodeType, - CodeLocation: node.runnerA.codeLocation, - State: node.outcome, - RunTime: node.runTime, - Failure: node.failure, - } -} - -func (node *synchronizedAfterSuiteNode) waitUntilOtherNodesAreDone(syncHost string) { - for { - if node.canRun(syncHost) { - return - } - - time.Sleep(50 * time.Millisecond) - } -} - -func (node *synchronizedAfterSuiteNode) canRun(syncHost string) bool { - resp, err := http.Get(syncHost + "/RemoteAfterSuiteData") - if err != nil || resp.StatusCode != http.StatusOK { - return false - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return false - } - resp.Body.Close() - - afterSuiteData := types.RemoteAfterSuiteData{} - err = json.Unmarshal(body, &afterSuiteData) - if err != nil { - return false - } - - return afterSuiteData.CanRun -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go deleted file mode 100644 index 4266a4b..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go +++ /dev/null @@ -1,196 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "sync" - - "github.com/onsi/gomega/ghttp" - "net/http" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "time" -) - -var _ = Describe("SynchronizedAfterSuiteNode", func() { - var failer *Failer.Failer - var node SuiteNode - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - var server *ghttp.Server - var things []string - var lock *sync.Mutex - - BeforeEach(func() { - things = []string{} - server = ghttp.NewServer() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - failer = Failer.New() - lock = &sync.Mutex{} - }) - - AfterEach(func() { - server.Close() - }) - - newNode := func(bodyA interface{}, bodyB interface{}) SuiteNode { - return NewSynchronizedAfterSuiteNode(bodyA, bodyB, codeLocation, time.Millisecond, failer) - } - - ranThing := func(thing string) { - lock.Lock() - defer lock.Unlock() - things = append(things, thing) - } - - thingsThatRan := func() []string { - lock.Lock() - defer lock.Unlock() - return things - } - - Context("when not running in parallel", func() { - Context("when all is well", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should run A, then B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "B"})) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Context("when A fails", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - failer.Fail("bam", innerCodeLocation) - }, func() { - ranThing("B") - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should still run B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "B"})) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - - Context("when B fails", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - failer.Fail("bam", innerCodeLocation) - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should run all the things", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "B"})) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - }) - - Context("when running in parallel", func() { - Context("as the first node", func() { - BeforeEach(func() { - server.AppendHandlers(ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/RemoteAfterSuiteData"), - func(writer http.ResponseWriter, request *http.Request) { - ranThing("Request1") - }, - ghttp.RespondWithJSONEncoded(200, types.RemoteAfterSuiteData{false}), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/RemoteAfterSuiteData"), - func(writer http.ResponseWriter, request *http.Request) { - ranThing("Request2") - }, - ghttp.RespondWithJSONEncoded(200, types.RemoteAfterSuiteData{false}), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/RemoteAfterSuiteData"), - func(writer http.ResponseWriter, request *http.Request) { - ranThing("Request3") - }, - ghttp.RespondWithJSONEncoded(200, types.RemoteAfterSuiteData{true}), - )) - - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - }) - - outcome = node.Run(1, 3, server.URL()) - }) - - It("should run A and, when the server says its time, run B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "Request1", "Request2", "Request3", "B"})) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Context("as any other node", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - }) - - outcome = node.Run(2, 3, server.URL()) - }) - - It("should run A, and not run B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A"})) - }) - - It("should not talk to the server", func() { - Ω(server.ReceivedRequests()).Should(BeEmpty()) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go deleted file mode 100644 index 76a9679..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go +++ /dev/null @@ -1,182 +0,0 @@ -package leafnodes - -import ( - "bytes" - "encoding/json" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "io/ioutil" - "net/http" - "reflect" - "time" -) - -type synchronizedBeforeSuiteNode struct { - runnerA *runner - runnerB *runner - - data []byte - - outcome types.SpecState - failure types.SpecFailure - runTime time.Duration -} - -func NewSynchronizedBeforeSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer) SuiteNode { - node := &synchronizedBeforeSuiteNode{} - - node.runnerA = newRunner(node.wrapA(bodyA), codeLocation, timeout, failer, types.SpecComponentTypeBeforeSuite, 0) - node.runnerB = newRunner(node.wrapB(bodyB), codeLocation, timeout, failer, types.SpecComponentTypeBeforeSuite, 0) - - return node -} - -func (node *synchronizedBeforeSuiteNode) Run(parallelNode int, parallelTotal int, syncHost string) bool { - t := time.Now() - defer func() { - node.runTime = time.Since(t) - }() - - if parallelNode == 1 { - node.outcome, node.failure = node.runA(parallelTotal, syncHost) - } else { - node.outcome, node.failure = node.waitForA(syncHost) - } - - if node.outcome != types.SpecStatePassed { - return false - } - node.outcome, node.failure = node.runnerB.run() - - return node.outcome == types.SpecStatePassed -} - -func (node *synchronizedBeforeSuiteNode) runA(parallelTotal int, syncHost string) (types.SpecState, types.SpecFailure) { - outcome, failure := node.runnerA.run() - - if parallelTotal > 1 { - state := types.RemoteBeforeSuiteStatePassed - if outcome != types.SpecStatePassed { - state = types.RemoteBeforeSuiteStateFailed - } - json := (types.RemoteBeforeSuiteData{ - Data: node.data, - State: state, - }).ToJSON() - http.Post(syncHost+"/BeforeSuiteState", "application/json", bytes.NewBuffer(json)) - } - - return outcome, failure -} - -func (node *synchronizedBeforeSuiteNode) waitForA(syncHost string) (types.SpecState, types.SpecFailure) { - failure := func(message string) types.SpecFailure { - return types.SpecFailure{ - Message: message, - Location: node.runnerA.codeLocation, - ComponentType: node.runnerA.nodeType, - ComponentIndex: node.runnerA.componentIndex, - ComponentCodeLocation: node.runnerA.codeLocation, - } - } - for { - resp, err := http.Get(syncHost + "/BeforeSuiteState") - if err != nil || resp.StatusCode != http.StatusOK { - return types.SpecStateFailed, failure("Failed to fetch BeforeSuite state") - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return types.SpecStateFailed, failure("Failed to read BeforeSuite state") - } - resp.Body.Close() - - beforeSuiteData := types.RemoteBeforeSuiteData{} - err = json.Unmarshal(body, &beforeSuiteData) - if err != nil { - return types.SpecStateFailed, failure("Failed to decode BeforeSuite state") - } - - switch beforeSuiteData.State { - case types.RemoteBeforeSuiteStatePassed: - node.data = beforeSuiteData.Data - return types.SpecStatePassed, types.SpecFailure{} - case types.RemoteBeforeSuiteStateFailed: - return types.SpecStateFailed, failure("BeforeSuite on Node 1 failed") - case types.RemoteBeforeSuiteStateDisappeared: - return types.SpecStateFailed, failure("Node 1 disappeared before completing BeforeSuite") - } - - time.Sleep(50 * time.Millisecond) - } - - return types.SpecStateFailed, failure("Shouldn't get here!") -} - -func (node *synchronizedBeforeSuiteNode) Passed() bool { - return node.outcome == types.SpecStatePassed -} - -func (node *synchronizedBeforeSuiteNode) Summary() *types.SetupSummary { - return &types.SetupSummary{ - ComponentType: node.runnerA.nodeType, - CodeLocation: node.runnerA.codeLocation, - State: node.outcome, - RunTime: node.runTime, - Failure: node.failure, - } -} - -func (node *synchronizedBeforeSuiteNode) wrapA(bodyA interface{}) interface{} { - typeA := reflect.TypeOf(bodyA) - if typeA.Kind() != reflect.Func { - panic("SynchronizedBeforeSuite expects a function as its first argument") - } - - takesNothing := typeA.NumIn() == 0 - takesADoneChannel := typeA.NumIn() == 1 && typeA.In(0).Kind() == reflect.Chan && typeA.In(0).Elem().Kind() == reflect.Interface - returnsBytes := typeA.NumOut() == 1 && typeA.Out(0).Kind() == reflect.Slice && typeA.Out(0).Elem().Kind() == reflect.Uint8 - - if !((takesNothing || takesADoneChannel) && returnsBytes) { - panic("SynchronizedBeforeSuite's first argument should be a function that returns []byte and either takes no arguments or takes a Done channel.") - } - - if takesADoneChannel { - return func(done chan<- interface{}) { - out := reflect.ValueOf(bodyA).Call([]reflect.Value{reflect.ValueOf(done)}) - node.data = out[0].Interface().([]byte) - } - } - - return func() { - out := reflect.ValueOf(bodyA).Call([]reflect.Value{}) - node.data = out[0].Interface().([]byte) - } -} - -func (node *synchronizedBeforeSuiteNode) wrapB(bodyB interface{}) interface{} { - typeB := reflect.TypeOf(bodyB) - if typeB.Kind() != reflect.Func { - panic("SynchronizedBeforeSuite expects a function as its second argument") - } - - returnsNothing := typeB.NumOut() == 0 - takesBytesOnly := typeB.NumIn() == 1 && typeB.In(0).Kind() == reflect.Slice && typeB.In(0).Elem().Kind() == reflect.Uint8 - takesBytesAndDone := typeB.NumIn() == 2 && - typeB.In(0).Kind() == reflect.Slice && typeB.In(0).Elem().Kind() == reflect.Uint8 && - typeB.In(1).Kind() == reflect.Chan && typeB.In(1).Elem().Kind() == reflect.Interface - - if !((takesBytesOnly || takesBytesAndDone) && returnsNothing) { - panic("SynchronizedBeforeSuite's second argument should be a function that returns nothing and either takes []byte or ([]byte, Done)") - } - - if takesBytesAndDone { - return func(done chan<- interface{}) { - reflect.ValueOf(bodyB).Call([]reflect.Value{reflect.ValueOf(node.data), reflect.ValueOf(done)}) - } - } - - return func() { - reflect.ValueOf(bodyB).Call([]reflect.Value{reflect.ValueOf(node.data)}) - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go deleted file mode 100644 index dbf2426..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go +++ /dev/null @@ -1,445 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "github.com/onsi/gomega/ghttp" - "net/http" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -var _ = Describe("SynchronizedBeforeSuiteNode", func() { - var failer *Failer.Failer - var node SuiteNode - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - var server *ghttp.Server - - BeforeEach(func() { - server = ghttp.NewServer() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - failer = Failer.New() - }) - - AfterEach(func() { - server.Close() - }) - - newNode := func(bodyA interface{}, bodyB interface{}) SuiteNode { - return NewSynchronizedBeforeSuiteNode(bodyA, bodyB, codeLocation, time.Millisecond, failer) - } - - Describe("when not running in parallel", func() { - Context("when all is well", func() { - var data []byte - BeforeEach(func() { - data = nil - - node = newNode(func() []byte { - return []byte("my data") - }, func(d []byte) { - data = d - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should run A, then B passing the output from A to B", func() { - Ω(data).Should(Equal([]byte("my data"))) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Context("when A fails", func() { - var ranB bool - BeforeEach(func() { - ranB = false - node = newNode(func() []byte { - failer.Fail("boom", innerCodeLocation) - return nil - }, func([]byte) { - ranB = true - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should not run B", func() { - Ω(ranB).Should(BeFalse()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - - Context("when B fails", func() { - BeforeEach(func() { - node = newNode(func() []byte { - return nil - }, func([]byte) { - failer.Fail("boom", innerCodeLocation) - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - - Context("when A times out", func() { - var ranB bool - BeforeEach(func() { - ranB = false - node = newNode(func(Done) []byte { - time.Sleep(time.Second) - return nil - }, func([]byte) { - ranB = true - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should not run B", func() { - Ω(ranB).Should(BeFalse()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateTimedOut)) - }) - }) - - Context("when B times out", func() { - BeforeEach(func() { - node = newNode(func() []byte { - return nil - }, func([]byte, Done) { - time.Sleep(time.Second) - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateTimedOut)) - }) - }) - }) - - Describe("when running in parallel", func() { - var ranB bool - var parallelNode, parallelTotal int - BeforeEach(func() { - ranB = false - parallelNode, parallelTotal = 1, 3 - }) - - Context("as the first node, it runs A", func() { - var expectedState types.RemoteBeforeSuiteData - - BeforeEach(func() { - parallelNode, parallelTotal = 1, 3 - }) - - JustBeforeEach(func() { - server.AppendHandlers(ghttp.CombineHandlers( - ghttp.VerifyRequest("POST", "/BeforeSuiteState"), - ghttp.VerifyJSONRepresenting(expectedState), - )) - - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - Context("when A succeeds", func() { - BeforeEach(func() { - expectedState = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStatePassed} - - node = newNode(func() []byte { - return []byte("my data") - }, func([]byte) { - ranB = true - }) - }) - - It("should post about A succeeding", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(1)) - }) - - It("should run B", func() { - Ω(ranB).Should(BeTrue()) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - }) - }) - - Context("when A fails", func() { - BeforeEach(func() { - expectedState = types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStateFailed} - - node = newNode(func() []byte { - panic("BAM") - return []byte("my data") - }, func([]byte) { - ranB = true - }) - }) - - It("should post about A failing", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(1)) - }) - - It("should not run B", func() { - Ω(ranB).Should(BeFalse()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - }) - }) - }) - - Context("as the Nth node", func() { - var statusCode int - var response interface{} - var ranA bool - var bData []byte - - BeforeEach(func() { - ranA = false - bData = nil - - statusCode = http.StatusOK - - server.AppendHandlers(ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/BeforeSuiteState"), - ghttp.RespondWith(http.StatusOK, string((types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending}).ToJSON())), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/BeforeSuiteState"), - ghttp.RespondWith(http.StatusOK, string((types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending}).ToJSON())), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/BeforeSuiteState"), - ghttp.RespondWithJSONEncodedPtr(&statusCode, &response), - )) - - node = newNode(func() []byte { - ranA = true - return nil - }, func(data []byte) { - bData = data - }) - - parallelNode, parallelTotal = 2, 3 - }) - - Context("when A on node1 succeeds", func() { - BeforeEach(func() { - response = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStatePassed} - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - It("should not run A", func() { - Ω(ranA).Should(BeFalse()) - }) - - It("should poll for A", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(3)) - }) - - It("should run B when the polling succeeds", func() { - Ω(bData).Should(Equal([]byte("my data"))) - }) - - It("should succeed", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - }) - }) - - Context("when A on node1 fails", func() { - BeforeEach(func() { - response = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStateFailed} - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - It("should not run A", func() { - Ω(ranA).Should(BeFalse()) - }) - - It("should poll for A", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(3)) - }) - - It("should not run B", func() { - Ω(bData).Should(BeNil()) - }) - - It("should fail", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - - summary := node.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("BeforeSuite on Node 1 failed")) - Ω(summary.Failure.Location).Should(Equal(codeLocation)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when node1 disappears", func() { - BeforeEach(func() { - response = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStateDisappeared} - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - It("should not run A", func() { - Ω(ranA).Should(BeFalse()) - }) - - It("should poll for A", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(3)) - }) - - It("should not run B", func() { - Ω(bData).Should(BeNil()) - }) - - It("should fail", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - - summary := node.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("Node 1 disappeared before completing BeforeSuite")) - Ω(summary.Failure.Location).Should(Equal(codeLocation)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - }) - }) - - Describe("construction", func() { - Describe("the first function", func() { - Context("when the first function returns a byte array", func() { - Context("and takes nothing", func() { - It("should be fine", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("and takes a done function", func() { - It("should be fine", func() { - Ω(func() { - newNode(func(Done) []byte { return nil }, func([]byte) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("and takes more than one thing", func() { - It("should panic", func() { - Ω(func() { - newNode(func(Done, Done) []byte { return nil }, func([]byte) {}) - }).Should(Panic()) - }) - }) - - Context("and takes something else", func() { - It("should panic", func() { - Ω(func() { - newNode(func(bool) []byte { return nil }, func([]byte) {}) - }).Should(Panic()) - }) - }) - }) - - Context("when the first function does not return a byte array", func() { - It("should panic", func() { - Ω(func() { - newNode(func() {}, func([]byte) {}) - }).Should(Panic()) - - Ω(func() { - newNode(func() []int { return nil }, func([]byte) {}) - }).Should(Panic()) - }) - }) - }) - - Describe("the second function", func() { - Context("when the second function takes a byte array", func() { - It("should be fine", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("when it also takes a done channel", func() { - It("should be fine", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte, Done) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("if it takes anything else", func() { - It("should panic", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte, chan bool) {}) - }).Should(Panic()) - - Ω(func() { - newNode(func() []byte { return nil }, func(string) {}) - }).Should(Panic()) - }) - }) - - Context("if it takes nothing at all", func() { - It("should panic", func() { - Ω(func() { - newNode(func() []byte { return nil }, func() {}) - }).Should(Panic()) - }) - }) - - Context("if it returns something", func() { - It("should panic", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte) []byte { return nil }) - }).Should(Panic()) - }) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/aggregator.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/aggregator.go deleted file mode 100644 index 9dcfb5f..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/aggregator.go +++ /dev/null @@ -1,250 +0,0 @@ -/* - -Aggregator is a reporter used by the Ginkgo CLI to aggregate and present parallel test output -coherently as tests complete. You shouldn't need to use this in your code. To run tests in parallel: - - ginkgo -nodes=N - -where N is the number of nodes you desire. -*/ -package remote - -import ( - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" -) - -type configAndSuite struct { - config config.GinkgoConfigType - summary *types.SuiteSummary -} - -type Aggregator struct { - nodeCount int - config config.DefaultReporterConfigType - stenographer stenographer.Stenographer - result chan bool - - suiteBeginnings chan configAndSuite - aggregatedSuiteBeginnings []configAndSuite - - beforeSuites chan *types.SetupSummary - aggregatedBeforeSuites []*types.SetupSummary - - afterSuites chan *types.SetupSummary - aggregatedAfterSuites []*types.SetupSummary - - specCompletions chan *types.SpecSummary - completedSpecs []*types.SpecSummary - - suiteEndings chan *types.SuiteSummary - aggregatedSuiteEndings []*types.SuiteSummary - specs []*types.SpecSummary - - startTime time.Time -} - -func NewAggregator(nodeCount int, result chan bool, config config.DefaultReporterConfigType, stenographer stenographer.Stenographer) *Aggregator { - aggregator := &Aggregator{ - nodeCount: nodeCount, - result: result, - config: config, - stenographer: stenographer, - - suiteBeginnings: make(chan configAndSuite, 0), - beforeSuites: make(chan *types.SetupSummary, 0), - afterSuites: make(chan *types.SetupSummary, 0), - specCompletions: make(chan *types.SpecSummary, 0), - suiteEndings: make(chan *types.SuiteSummary, 0), - } - - go aggregator.mux() - - return aggregator -} - -func (aggregator *Aggregator) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - aggregator.suiteBeginnings <- configAndSuite{config, summary} -} - -func (aggregator *Aggregator) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - aggregator.beforeSuites <- setupSummary -} - -func (aggregator *Aggregator) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - aggregator.afterSuites <- setupSummary -} - -func (aggregator *Aggregator) SpecWillRun(specSummary *types.SpecSummary) { - //noop -} - -func (aggregator *Aggregator) SpecDidComplete(specSummary *types.SpecSummary) { - aggregator.specCompletions <- specSummary -} - -func (aggregator *Aggregator) SpecSuiteDidEnd(summary *types.SuiteSummary) { - aggregator.suiteEndings <- summary -} - -func (aggregator *Aggregator) mux() { -loop: - for { - select { - case configAndSuite := <-aggregator.suiteBeginnings: - aggregator.registerSuiteBeginning(configAndSuite) - case setupSummary := <-aggregator.beforeSuites: - aggregator.registerBeforeSuite(setupSummary) - case setupSummary := <-aggregator.afterSuites: - aggregator.registerAfterSuite(setupSummary) - case specSummary := <-aggregator.specCompletions: - aggregator.registerSpecCompletion(specSummary) - case suite := <-aggregator.suiteEndings: - finished, passed := aggregator.registerSuiteEnding(suite) - if finished { - aggregator.result <- passed - break loop - } - } - } -} - -func (aggregator *Aggregator) registerSuiteBeginning(configAndSuite configAndSuite) { - aggregator.aggregatedSuiteBeginnings = append(aggregator.aggregatedSuiteBeginnings, configAndSuite) - - if len(aggregator.aggregatedSuiteBeginnings) == 1 { - aggregator.startTime = time.Now() - } - - if len(aggregator.aggregatedSuiteBeginnings) != aggregator.nodeCount { - return - } - - aggregator.stenographer.AnnounceSuite(configAndSuite.summary.SuiteDescription, configAndSuite.config.RandomSeed, configAndSuite.config.RandomizeAllSpecs, aggregator.config.Succinct) - - numberOfSpecsToRun := 0 - totalNumberOfSpecs := 0 - for _, configAndSuite := range aggregator.aggregatedSuiteBeginnings { - numberOfSpecsToRun += configAndSuite.summary.NumberOfSpecsThatWillBeRun - totalNumberOfSpecs += configAndSuite.summary.NumberOfTotalSpecs - } - - aggregator.stenographer.AnnounceNumberOfSpecs(numberOfSpecsToRun, totalNumberOfSpecs, aggregator.config.Succinct) - aggregator.stenographer.AnnounceAggregatedParallelRun(aggregator.nodeCount, aggregator.config.Succinct) - aggregator.flushCompletedSpecs() -} - -func (aggregator *Aggregator) registerBeforeSuite(setupSummary *types.SetupSummary) { - aggregator.aggregatedBeforeSuites = append(aggregator.aggregatedBeforeSuites, setupSummary) - aggregator.flushCompletedSpecs() -} - -func (aggregator *Aggregator) registerAfterSuite(setupSummary *types.SetupSummary) { - aggregator.aggregatedAfterSuites = append(aggregator.aggregatedAfterSuites, setupSummary) - aggregator.flushCompletedSpecs() -} - -func (aggregator *Aggregator) registerSpecCompletion(specSummary *types.SpecSummary) { - aggregator.completedSpecs = append(aggregator.completedSpecs, specSummary) - aggregator.specs = append(aggregator.specs, specSummary) - aggregator.flushCompletedSpecs() -} - -func (aggregator *Aggregator) flushCompletedSpecs() { - if len(aggregator.aggregatedSuiteBeginnings) != aggregator.nodeCount { - return - } - - for _, setupSummary := range aggregator.aggregatedBeforeSuites { - aggregator.announceBeforeSuite(setupSummary) - } - - for _, specSummary := range aggregator.completedSpecs { - aggregator.announceSpec(specSummary) - } - - for _, setupSummary := range aggregator.aggregatedAfterSuites { - aggregator.announceAfterSuite(setupSummary) - } - - aggregator.aggregatedBeforeSuites = []*types.SetupSummary{} - aggregator.completedSpecs = []*types.SpecSummary{} - aggregator.aggregatedAfterSuites = []*types.SetupSummary{} -} - -func (aggregator *Aggregator) announceBeforeSuite(setupSummary *types.SetupSummary) { - aggregator.stenographer.AnnounceCapturedOutput(setupSummary.CapturedOutput) - if setupSummary.State != types.SpecStatePassed { - aggregator.stenographer.AnnounceBeforeSuiteFailure(setupSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - } -} - -func (aggregator *Aggregator) announceAfterSuite(setupSummary *types.SetupSummary) { - aggregator.stenographer.AnnounceCapturedOutput(setupSummary.CapturedOutput) - if setupSummary.State != types.SpecStatePassed { - aggregator.stenographer.AnnounceAfterSuiteFailure(setupSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - } -} - -func (aggregator *Aggregator) announceSpec(specSummary *types.SpecSummary) { - if aggregator.config.Verbose && specSummary.State != types.SpecStatePending && specSummary.State != types.SpecStateSkipped { - aggregator.stenographer.AnnounceSpecWillRun(specSummary) - } - - aggregator.stenographer.AnnounceCapturedOutput(specSummary.CapturedOutput) - - switch specSummary.State { - case types.SpecStatePassed: - if specSummary.IsMeasurement { - aggregator.stenographer.AnnounceSuccesfulMeasurement(specSummary, aggregator.config.Succinct) - } else if specSummary.RunTime.Seconds() >= aggregator.config.SlowSpecThreshold { - aggregator.stenographer.AnnounceSuccesfulSlowSpec(specSummary, aggregator.config.Succinct) - } else { - aggregator.stenographer.AnnounceSuccesfulSpec(specSummary) - } - - case types.SpecStatePending: - aggregator.stenographer.AnnouncePendingSpec(specSummary, aggregator.config.NoisyPendings && !aggregator.config.Succinct) - case types.SpecStateSkipped: - aggregator.stenographer.AnnounceSkippedSpec(specSummary) - case types.SpecStateTimedOut: - aggregator.stenographer.AnnounceSpecTimedOut(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - case types.SpecStatePanicked: - aggregator.stenographer.AnnounceSpecPanicked(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - case types.SpecStateFailed: - aggregator.stenographer.AnnounceSpecFailed(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - } -} - -func (aggregator *Aggregator) registerSuiteEnding(suite *types.SuiteSummary) (finished bool, passed bool) { - aggregator.aggregatedSuiteEndings = append(aggregator.aggregatedSuiteEndings, suite) - if len(aggregator.aggregatedSuiteEndings) < aggregator.nodeCount { - return false, false - } - - aggregatedSuiteSummary := &types.SuiteSummary{} - aggregatedSuiteSummary.SuiteSucceeded = true - - for _, suiteSummary := range aggregator.aggregatedSuiteEndings { - if suiteSummary.SuiteSucceeded == false { - aggregatedSuiteSummary.SuiteSucceeded = false - } - - aggregatedSuiteSummary.NumberOfSpecsThatWillBeRun += suiteSummary.NumberOfSpecsThatWillBeRun - aggregatedSuiteSummary.NumberOfTotalSpecs += suiteSummary.NumberOfTotalSpecs - aggregatedSuiteSummary.NumberOfPassedSpecs += suiteSummary.NumberOfPassedSpecs - aggregatedSuiteSummary.NumberOfFailedSpecs += suiteSummary.NumberOfFailedSpecs - aggregatedSuiteSummary.NumberOfPendingSpecs += suiteSummary.NumberOfPendingSpecs - aggregatedSuiteSummary.NumberOfSkippedSpecs += suiteSummary.NumberOfSkippedSpecs - } - - aggregatedSuiteSummary.RunTime = time.Since(aggregator.startTime) - - aggregator.stenographer.SummarizeFailures(aggregator.specs) - aggregator.stenographer.AnnounceSpecRunCompletion(aggregatedSuiteSummary, aggregator.config.Succinct) - - return true, aggregatedSuiteSummary.SuiteSucceeded -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/aggregator_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/aggregator_test.go deleted file mode 100644 index 377a016..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/aggregator_test.go +++ /dev/null @@ -1,311 +0,0 @@ -package remote_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/config" - . "github.com/onsi/ginkgo/internal/remote" - st "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" - "time" -) - -var _ = Describe("Aggregator", func() { - var ( - aggregator *Aggregator - reporterConfig config.DefaultReporterConfigType - stenographer *st.FakeStenographer - result chan bool - - ginkgoConfig1 config.GinkgoConfigType - ginkgoConfig2 config.GinkgoConfigType - - suiteSummary1 *types.SuiteSummary - suiteSummary2 *types.SuiteSummary - - beforeSummary *types.SetupSummary - afterSummary *types.SetupSummary - specSummary *types.SpecSummary - - suiteDescription string - ) - - BeforeEach(func() { - reporterConfig = config.DefaultReporterConfigType{ - NoColor: false, - SlowSpecThreshold: 0.1, - NoisyPendings: true, - Succinct: false, - Verbose: true, - } - stenographer = st.NewFakeStenographer() - result = make(chan bool, 1) - aggregator = NewAggregator(2, result, reporterConfig, stenographer) - - // - // now set up some fixture data - // - - ginkgoConfig1 = config.GinkgoConfigType{ - RandomSeed: 1138, - RandomizeAllSpecs: true, - ParallelNode: 1, - ParallelTotal: 2, - } - - ginkgoConfig2 = config.GinkgoConfigType{ - RandomSeed: 1138, - RandomizeAllSpecs: true, - ParallelNode: 2, - ParallelTotal: 2, - } - - suiteDescription = "My Parallel Suite" - - suiteSummary1 = &types.SuiteSummary{ - SuiteDescription: suiteDescription, - - NumberOfSpecsBeforeParallelization: 30, - NumberOfTotalSpecs: 17, - NumberOfSpecsThatWillBeRun: 15, - NumberOfPendingSpecs: 1, - NumberOfSkippedSpecs: 1, - } - - suiteSummary2 = &types.SuiteSummary{ - SuiteDescription: suiteDescription, - - NumberOfSpecsBeforeParallelization: 30, - NumberOfTotalSpecs: 13, - NumberOfSpecsThatWillBeRun: 8, - NumberOfPendingSpecs: 2, - NumberOfSkippedSpecs: 3, - } - - beforeSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - CapturedOutput: "BeforeSuiteOutput", - } - - afterSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - CapturedOutput: "AfterSuiteOutput", - } - - specSummary = &types.SpecSummary{ - State: types.SpecStatePassed, - CapturedOutput: "SpecOutput", - } - }) - - call := func(method string, args ...interface{}) st.FakeStenographerCall { - return st.NewFakeStenographerCall(method, args...) - } - - beginSuite := func() { - stenographer.Reset() - aggregator.SpecSuiteWillBegin(ginkgoConfig2, suiteSummary2) - aggregator.SpecSuiteWillBegin(ginkgoConfig1, suiteSummary1) - Eventually(func() interface{} { - return len(stenographer.Calls()) - }).Should(BeNumerically(">=", 3)) - } - - Describe("Announcing the beginning of the suite", func() { - Context("When one of the parallel-suites starts", func() { - BeforeEach(func() { - aggregator.SpecSuiteWillBegin(ginkgoConfig2, suiteSummary2) - }) - - It("should be silent", func() { - Consistently(func() interface{} { return stenographer.Calls() }).Should(BeEmpty()) - }) - }) - - Context("once all of the parallel-suites have started", func() { - BeforeEach(func() { - aggregator.SpecSuiteWillBegin(ginkgoConfig2, suiteSummary2) - aggregator.SpecSuiteWillBegin(ginkgoConfig1, suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(3)) - }) - - It("should announce the beginning of the suite", func() { - Ω(stenographer.Calls()).Should(HaveLen(3)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuite", suiteDescription, ginkgoConfig1.RandomSeed, true, false))) - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceNumberOfSpecs", 23, 30, false))) - Ω(stenographer.Calls()[2]).Should(Equal(call("AnnounceAggregatedParallelRun", 2, false))) - }) - }) - }) - - Describe("Announcing specs and before suites", func() { - Context("when the parallel-suites have not all started", func() { - BeforeEach(func() { - aggregator.BeforeSuiteDidRun(beforeSummary) - aggregator.AfterSuiteDidRun(afterSummary) - aggregator.SpecDidComplete(specSummary) - }) - - It("should not announce any specs", func() { - Consistently(func() interface{} { return stenographer.Calls() }).Should(BeEmpty()) - }) - - Context("when the parallel-suites subsequently start", func() { - BeforeEach(func() { - beginSuite() - }) - - It("should announce the specs, the before suites and the after suites", func() { - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(ContainElement(call("AnnounceSuccesfulSpec", specSummary))) - - Ω(stenographer.Calls()).Should(ContainElement(call("AnnounceCapturedOutput", beforeSummary.CapturedOutput))) - Ω(stenographer.Calls()).Should(ContainElement(call("AnnounceCapturedOutput", afterSummary.CapturedOutput))) - }) - }) - }) - - Context("When the parallel-suites have all started", func() { - BeforeEach(func() { - beginSuite() - stenographer.Reset() - }) - - Context("When a spec completes", func() { - BeforeEach(func() { - aggregator.BeforeSuiteDidRun(beforeSummary) - aggregator.SpecDidComplete(specSummary) - aggregator.AfterSuiteDidRun(afterSummary) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(5)) - }) - - It("should announce the captured output of the BeforeSuite", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceCapturedOutput", beforeSummary.CapturedOutput))) - }) - - It("should announce that the spec will run (when in verbose mode)", func() { - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceSpecWillRun", specSummary))) - }) - - It("should announce the captured stdout of the spec", func() { - Ω(stenographer.Calls()[2]).Should(Equal(call("AnnounceCapturedOutput", specSummary.CapturedOutput))) - }) - - It("should announce completion", func() { - Ω(stenographer.Calls()[3]).Should(Equal(call("AnnounceSuccesfulSpec", specSummary))) - }) - - It("should announce the captured output of the AfterSuite", func() { - Ω(stenographer.Calls()[4]).Should(Equal(call("AnnounceCapturedOutput", afterSummary.CapturedOutput))) - }) - }) - }) - }) - - Describe("Announcing the end of the suite", func() { - BeforeEach(func() { - beginSuite() - stenographer.Reset() - }) - - Context("When one of the parallel-suites ends", func() { - BeforeEach(func() { - aggregator.SpecSuiteDidEnd(suiteSummary2) - }) - - It("should be silent", func() { - Consistently(func() interface{} { return stenographer.Calls() }).Should(BeEmpty()) - }) - - It("should not notify the channel", func() { - Ω(result).Should(BeEmpty()) - }) - }) - - Context("once all of the parallel-suites end", func() { - BeforeEach(func() { - time.Sleep(200 * time.Millisecond) - - suiteSummary1.SuiteSucceeded = true - suiteSummary1.NumberOfPassedSpecs = 15 - suiteSummary1.NumberOfFailedSpecs = 0 - suiteSummary2.SuiteSucceeded = false - suiteSummary2.NumberOfPassedSpecs = 5 - suiteSummary2.NumberOfFailedSpecs = 3 - - aggregator.SpecSuiteDidEnd(suiteSummary2) - aggregator.SpecSuiteDidEnd(suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(2)) - }) - - It("should announce the end of the suite", func() { - compositeSummary := stenographer.Calls()[1].Args[0].(*types.SuiteSummary) - - Ω(compositeSummary.SuiteSucceeded).Should(BeFalse()) - Ω(compositeSummary.NumberOfSpecsThatWillBeRun).Should(Equal(23)) - Ω(compositeSummary.NumberOfTotalSpecs).Should(Equal(30)) - Ω(compositeSummary.NumberOfPassedSpecs).Should(Equal(20)) - Ω(compositeSummary.NumberOfFailedSpecs).Should(Equal(3)) - Ω(compositeSummary.NumberOfPendingSpecs).Should(Equal(3)) - Ω(compositeSummary.NumberOfSkippedSpecs).Should(Equal(4)) - Ω(compositeSummary.RunTime.Seconds()).Should(BeNumerically(">", 0.2)) - }) - }) - - Context("when all the parallel-suites pass", func() { - BeforeEach(func() { - suiteSummary1.SuiteSucceeded = true - suiteSummary2.SuiteSucceeded = true - - aggregator.SpecSuiteDidEnd(suiteSummary2) - aggregator.SpecSuiteDidEnd(suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(2)) - }) - - It("should report success", func() { - compositeSummary := stenographer.Calls()[1].Args[0].(*types.SuiteSummary) - - Ω(compositeSummary.SuiteSucceeded).Should(BeTrue()) - }) - - It("should notify the channel that it succeded", func(done Done) { - Ω(<-result).Should(BeTrue()) - close(done) - }) - }) - - Context("when one of the parallel-suites fails", func() { - BeforeEach(func() { - suiteSummary1.SuiteSucceeded = true - suiteSummary2.SuiteSucceeded = false - - aggregator.SpecSuiteDidEnd(suiteSummary2) - aggregator.SpecSuiteDidEnd(suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(2)) - }) - - It("should report failure", func() { - compositeSummary := stenographer.Calls()[1].Args[0].(*types.SuiteSummary) - - Ω(compositeSummary.SuiteSucceeded).Should(BeFalse()) - }) - - It("should notify the channel that it failed", func(done Done) { - Ω(<-result).Should(BeFalse()) - close(done) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go deleted file mode 100644 index a928f93..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package remote_test - -type fakeOutputInterceptor struct { - DidStartInterceptingOutput bool - DidStopInterceptingOutput bool - InterceptedOutput string -} - -func (interceptor *fakeOutputInterceptor) StartInterceptingOutput() error { - interceptor.DidStartInterceptingOutput = true - return nil -} - -func (interceptor *fakeOutputInterceptor) StopInterceptingAndReturnOutput() (string, error) { - interceptor.DidStopInterceptingOutput = true - return interceptor.InterceptedOutput, nil -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go deleted file mode 100644 index 3543c59..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package remote_test - -import ( - "io" - "io/ioutil" - "net/http" -) - -type post struct { - url string - bodyType string - bodyContent []byte -} - -type fakePoster struct { - posts []post -} - -func newFakePoster() *fakePoster { - return &fakePoster{ - posts: make([]post, 0), - } -} - -func (poster *fakePoster) Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error) { - bodyContent, _ := ioutil.ReadAll(body) - poster.posts = append(poster.posts, post{ - url: url, - bodyType: bodyType, - bodyContent: bodyContent, - }) - return nil, nil -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/forwarding_reporter.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/forwarding_reporter.go deleted file mode 100644 index 025eb50..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/forwarding_reporter.go +++ /dev/null @@ -1,90 +0,0 @@ -package remote - -import ( - "bytes" - "encoding/json" - "io" - "net/http" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" -) - -//An interface to net/http's client to allow the injection of fakes under test -type Poster interface { - Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error) -} - -/* -The ForwardingReporter is a Ginkgo reporter that forwards information to -a Ginkgo remote server. - -When streaming parallel test output, this repoter is automatically installed by Ginkgo. - -This is accomplished by passing in the GINKGO_REMOTE_REPORTING_SERVER environment variable to `go test`, the Ginkgo test runner -detects this environment variable (which should contain the host of the server) and automatically installs a ForwardingReporter -in place of Ginkgo's DefaultReporter. -*/ - -type ForwardingReporter struct { - serverHost string - poster Poster - outputInterceptor OutputInterceptor -} - -func NewForwardingReporter(serverHost string, poster Poster, outputInterceptor OutputInterceptor) *ForwardingReporter { - return &ForwardingReporter{ - serverHost: serverHost, - poster: poster, - outputInterceptor: outputInterceptor, - } -} - -func (reporter *ForwardingReporter) post(path string, data interface{}) { - encoded, _ := json.Marshal(data) - buffer := bytes.NewBuffer(encoded) - reporter.poster.Post(reporter.serverHost+path, "application/json", buffer) -} - -func (reporter *ForwardingReporter) SpecSuiteWillBegin(conf config.GinkgoConfigType, summary *types.SuiteSummary) { - data := struct { - Config config.GinkgoConfigType `json:"config"` - Summary *types.SuiteSummary `json:"suite-summary"` - }{ - conf, - summary, - } - - reporter.outputInterceptor.StartInterceptingOutput() - reporter.post("/SpecSuiteWillBegin", data) -} - -func (reporter *ForwardingReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - output, _ := reporter.outputInterceptor.StopInterceptingAndReturnOutput() - reporter.outputInterceptor.StartInterceptingOutput() - setupSummary.CapturedOutput = output - reporter.post("/BeforeSuiteDidRun", setupSummary) -} - -func (reporter *ForwardingReporter) SpecWillRun(specSummary *types.SpecSummary) { - reporter.post("/SpecWillRun", specSummary) -} - -func (reporter *ForwardingReporter) SpecDidComplete(specSummary *types.SpecSummary) { - output, _ := reporter.outputInterceptor.StopInterceptingAndReturnOutput() - reporter.outputInterceptor.StartInterceptingOutput() - specSummary.CapturedOutput = output - reporter.post("/SpecDidComplete", specSummary) -} - -func (reporter *ForwardingReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - output, _ := reporter.outputInterceptor.StopInterceptingAndReturnOutput() - reporter.outputInterceptor.StartInterceptingOutput() - setupSummary.CapturedOutput = output - reporter.post("/AfterSuiteDidRun", setupSummary) -} - -func (reporter *ForwardingReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - reporter.outputInterceptor.StopInterceptingAndReturnOutput() - reporter.post("/SpecSuiteDidEnd", summary) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go deleted file mode 100644 index e5f3b1e..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go +++ /dev/null @@ -1,180 +0,0 @@ -package remote_test - -import ( - "encoding/json" - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - . "github.com/onsi/ginkgo/internal/remote" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("ForwardingReporter", func() { - var ( - reporter *ForwardingReporter - interceptor *fakeOutputInterceptor - poster *fakePoster - suiteSummary *types.SuiteSummary - specSummary *types.SpecSummary - setupSummary *types.SetupSummary - serverHost string - ) - - BeforeEach(func() { - serverHost = "http://127.0.0.1:7788" - - poster = newFakePoster() - - interceptor = &fakeOutputInterceptor{ - InterceptedOutput: "The intercepted output!", - } - - reporter = NewForwardingReporter(serverHost, poster, interceptor) - - suiteSummary = &types.SuiteSummary{ - SuiteDescription: "My Test Suite", - } - - setupSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - } - - specSummary = &types.SpecSummary{ - ComponentTexts: []string{"My", "Spec"}, - State: types.SpecStatePassed, - } - }) - - Context("When a suite begins", func() { - BeforeEach(func() { - reporter.SpecSuiteWillBegin(config.GinkgoConfig, suiteSummary) - }) - - It("should start intercepting output", func() { - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - - It("should POST the SuiteSummary and Ginkgo Config to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/SpecSuiteWillBegin")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var sentData struct { - SentConfig config.GinkgoConfigType `json:"config"` - SentSuiteSummary *types.SuiteSummary `json:"suite-summary"` - } - - err := json.Unmarshal(poster.posts[0].bodyContent, &sentData) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(sentData.SentConfig).Should(Equal(config.GinkgoConfig)) - Ω(sentData.SentSuiteSummary).Should(Equal(suiteSummary)) - }) - }) - - Context("when a BeforeSuite completes", func() { - BeforeEach(func() { - reporter.BeforeSuiteDidRun(setupSummary) - }) - - It("should stop, then start intercepting output", func() { - Ω(interceptor.DidStopInterceptingOutput).Should(BeTrue()) - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - - It("should POST the SetupSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/BeforeSuiteDidRun")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SetupSummary - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - setupSummary.CapturedOutput = interceptor.InterceptedOutput - Ω(summary).Should(Equal(setupSummary)) - }) - }) - - Context("when an AfterSuite completes", func() { - BeforeEach(func() { - reporter.AfterSuiteDidRun(setupSummary) - }) - - It("should stop, then start intercepting output", func() { - Ω(interceptor.DidStopInterceptingOutput).Should(BeTrue()) - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - - It("should POST the SetupSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/AfterSuiteDidRun")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SetupSummary - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - setupSummary.CapturedOutput = interceptor.InterceptedOutput - Ω(summary).Should(Equal(setupSummary)) - }) - }) - - Context("When a spec will run", func() { - BeforeEach(func() { - reporter.SpecWillRun(specSummary) - }) - - It("should POST the SpecSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/SpecWillRun")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SpecSummary - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - Ω(summary).Should(Equal(specSummary)) - }) - - Context("When a spec completes", func() { - BeforeEach(func() { - specSummary.State = types.SpecStatePanicked - reporter.SpecDidComplete(specSummary) - }) - - It("should POST the SpecSummary to the Ginkgo server and include any intercepted output", func() { - Ω(poster.posts).Should(HaveLen(2)) - Ω(poster.posts[1].url).Should(Equal("http://127.0.0.1:7788/SpecDidComplete")) - Ω(poster.posts[1].bodyType).Should(Equal("application/json")) - - var summary *types.SpecSummary - err := json.Unmarshal(poster.posts[1].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - specSummary.CapturedOutput = interceptor.InterceptedOutput - Ω(summary).Should(Equal(specSummary)) - }) - - It("should stop, then start intercepting output", func() { - Ω(interceptor.DidStopInterceptingOutput).Should(BeTrue()) - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - }) - }) - - Context("When a suite ends", func() { - BeforeEach(func() { - reporter.SpecSuiteDidEnd(suiteSummary) - }) - - It("should POST the SuiteSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/SpecSuiteDidEnd")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SuiteSummary - - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(summary).Should(Equal(suiteSummary)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/output_interceptor.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/output_interceptor.go deleted file mode 100644 index 093f451..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/output_interceptor.go +++ /dev/null @@ -1,10 +0,0 @@ -package remote - -/* -The OutputInterceptor is used by the ForwardingReporter to -intercept and capture all stdin and stderr output during a test run. -*/ -type OutputInterceptor interface { - StartInterceptingOutput() error - StopInterceptingAndReturnOutput() (string, error) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/output_interceptor_unix.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/output_interceptor_unix.go deleted file mode 100644 index 181b227..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/output_interceptor_unix.go +++ /dev/null @@ -1,52 +0,0 @@ -// +build freebsd openbsd netbsd dragonfly darwin linux - -package remote - -import ( - "errors" - "io/ioutil" - "os" - "syscall" -) - -func NewOutputInterceptor() OutputInterceptor { - return &outputInterceptor{} -} - -type outputInterceptor struct { - redirectFile *os.File - intercepting bool -} - -func (interceptor *outputInterceptor) StartInterceptingOutput() error { - if interceptor.intercepting { - return errors.New("Already intercepting output!") - } - interceptor.intercepting = true - - var err error - - interceptor.redirectFile, err = ioutil.TempFile("", "ginkgo-output") - if err != nil { - return err - } - - syscall.Dup2(int(interceptor.redirectFile.Fd()), 1) - syscall.Dup2(int(interceptor.redirectFile.Fd()), 2) - - return nil -} - -func (interceptor *outputInterceptor) StopInterceptingAndReturnOutput() (string, error) { - if !interceptor.intercepting { - return "", errors.New("Not intercepting output!") - } - - interceptor.redirectFile.Close() - output, err := ioutil.ReadFile(interceptor.redirectFile.Name()) - os.Remove(interceptor.redirectFile.Name()) - - interceptor.intercepting = false - - return string(output), err -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/output_interceptor_win.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/output_interceptor_win.go deleted file mode 100644 index c8f97d9..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/output_interceptor_win.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build windows - -package remote - -import ( - "errors" -) - -func NewOutputInterceptor() OutputInterceptor { - return &outputInterceptor{} -} - -type outputInterceptor struct { - intercepting bool -} - -func (interceptor *outputInterceptor) StartInterceptingOutput() error { - if interceptor.intercepting { - return errors.New("Already intercepting output!") - } - interceptor.intercepting = true - - // not working on windows... - - return nil -} - -func (interceptor *outputInterceptor) StopInterceptingAndReturnOutput() (string, error) { - // not working on windows... - interceptor.intercepting = false - - return "", nil -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go deleted file mode 100644 index e6b4e9f..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package remote_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestRemote(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Remote Spec Forwarding Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/server.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/server.go deleted file mode 100644 index b55c681..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/server.go +++ /dev/null @@ -1,204 +0,0 @@ -/* - -The remote package provides the pieces to allow Ginkgo test suites to report to remote listeners. -This is used, primarily, to enable streaming parallel test output but has, in principal, broader applications (e.g. streaming test output to a browser). - -*/ - -package remote - -import ( - "encoding/json" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - "io/ioutil" - "net" - "net/http" - "sync" -) - -/* -Server spins up on an automatically selected port and listens for communication from the forwarding reporter. -It then forwards that communication to attached reporters. -*/ -type Server struct { - listener net.Listener - reporters []reporters.Reporter - alives []func() bool - lock *sync.Mutex - beforeSuiteData types.RemoteBeforeSuiteData - parallelTotal int -} - -//Create a new server, automatically selecting a port -func NewServer(parallelTotal int) (*Server, error) { - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - return nil, err - } - return &Server{ - listener: listener, - lock: &sync.Mutex{}, - alives: make([]func() bool, parallelTotal), - beforeSuiteData: types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending}, - parallelTotal: parallelTotal, - }, nil -} - -//Start the server. You don't need to `go s.Start()`, just `s.Start()` -func (server *Server) Start() { - httpServer := &http.Server{} - mux := http.NewServeMux() - httpServer.Handler = mux - - //streaming endpoints - mux.HandleFunc("/SpecSuiteWillBegin", server.specSuiteWillBegin) - mux.HandleFunc("/BeforeSuiteDidRun", server.beforeSuiteDidRun) - mux.HandleFunc("/AfterSuiteDidRun", server.afterSuiteDidRun) - mux.HandleFunc("/SpecWillRun", server.specWillRun) - mux.HandleFunc("/SpecDidComplete", server.specDidComplete) - mux.HandleFunc("/SpecSuiteDidEnd", server.specSuiteDidEnd) - - //synchronization endpoints - mux.HandleFunc("/BeforeSuiteState", server.handleBeforeSuiteState) - mux.HandleFunc("/RemoteAfterSuiteData", server.handleRemoteAfterSuiteData) - - go httpServer.Serve(server.listener) -} - -//Stop the server -func (server *Server) Close() { - server.listener.Close() -} - -//The address the server can be reached it. Pass this into the `ForwardingReporter`. -func (server *Server) Address() string { - return "http://" + server.listener.Addr().String() -} - -// -// Streaming Endpoints -// - -//The server will forward all received messages to Ginkgo reporters registered with `RegisterReporters` -func (server *Server) readAll(request *http.Request) []byte { - defer request.Body.Close() - body, _ := ioutil.ReadAll(request.Body) - return body -} - -func (server *Server) RegisterReporters(reporters ...reporters.Reporter) { - server.reporters = reporters -} - -func (server *Server) specSuiteWillBegin(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - - var data struct { - Config config.GinkgoConfigType `json:"config"` - Summary *types.SuiteSummary `json:"suite-summary"` - } - - json.Unmarshal(body, &data) - - for _, reporter := range server.reporters { - reporter.SpecSuiteWillBegin(data.Config, data.Summary) - } -} - -func (server *Server) beforeSuiteDidRun(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var setupSummary *types.SetupSummary - json.Unmarshal(body, &setupSummary) - - for _, reporter := range server.reporters { - reporter.BeforeSuiteDidRun(setupSummary) - } -} - -func (server *Server) afterSuiteDidRun(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var setupSummary *types.SetupSummary - json.Unmarshal(body, &setupSummary) - - for _, reporter := range server.reporters { - reporter.AfterSuiteDidRun(setupSummary) - } -} - -func (server *Server) specWillRun(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var specSummary *types.SpecSummary - json.Unmarshal(body, &specSummary) - - for _, reporter := range server.reporters { - reporter.SpecWillRun(specSummary) - } -} - -func (server *Server) specDidComplete(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var specSummary *types.SpecSummary - json.Unmarshal(body, &specSummary) - - for _, reporter := range server.reporters { - reporter.SpecDidComplete(specSummary) - } -} - -func (server *Server) specSuiteDidEnd(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var suiteSummary *types.SuiteSummary - json.Unmarshal(body, &suiteSummary) - - for _, reporter := range server.reporters { - reporter.SpecSuiteDidEnd(suiteSummary) - } -} - -// -// Synchronization Endpoints -// - -func (server *Server) RegisterAlive(node int, alive func() bool) { - server.lock.Lock() - defer server.lock.Unlock() - server.alives[node-1] = alive -} - -func (server *Server) nodeIsAlive(node int) bool { - server.lock.Lock() - defer server.lock.Unlock() - alive := server.alives[node-1] - if alive == nil { - return true - } - return alive() -} - -func (server *Server) handleBeforeSuiteState(writer http.ResponseWriter, request *http.Request) { - if request.Method == "POST" { - dec := json.NewDecoder(request.Body) - dec.Decode(&(server.beforeSuiteData)) - } else { - beforeSuiteData := server.beforeSuiteData - if beforeSuiteData.State == types.RemoteBeforeSuiteStatePending && !server.nodeIsAlive(1) { - beforeSuiteData.State = types.RemoteBeforeSuiteStateDisappeared - } - enc := json.NewEncoder(writer) - enc.Encode(beforeSuiteData) - } -} - -func (server *Server) handleRemoteAfterSuiteData(writer http.ResponseWriter, request *http.Request) { - afterSuiteData := types.RemoteAfterSuiteData{ - CanRun: true, - } - for i := 2; i <= server.parallelTotal; i++ { - afterSuiteData.CanRun = afterSuiteData.CanRun && !server.nodeIsAlive(i) - } - - enc := json.NewEncoder(writer) - enc.Encode(afterSuiteData) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/server_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/server_test.go deleted file mode 100644 index eb2eefe..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/server_test.go +++ /dev/null @@ -1,269 +0,0 @@ -package remote_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/remote" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - - "bytes" - "encoding/json" - "net/http" -) - -var _ = Describe("Server", func() { - var ( - server *Server - ) - - BeforeEach(func() { - var err error - server, err = NewServer(3) - Ω(err).ShouldNot(HaveOccurred()) - - server.Start() - }) - - AfterEach(func() { - server.Close() - }) - - Describe("Streaming endpoints", func() { - var ( - reporterA, reporterB *reporters.FakeReporter - forwardingReporter *ForwardingReporter - - suiteSummary *types.SuiteSummary - setupSummary *types.SetupSummary - specSummary *types.SpecSummary - ) - - BeforeEach(func() { - reporterA = reporters.NewFakeReporter() - reporterB = reporters.NewFakeReporter() - - server.RegisterReporters(reporterA, reporterB) - - forwardingReporter = NewForwardingReporter(server.Address(), &http.Client{}, &fakeOutputInterceptor{}) - - suiteSummary = &types.SuiteSummary{ - SuiteDescription: "My Test Suite", - } - - setupSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - } - - specSummary = &types.SpecSummary{ - ComponentTexts: []string{"My", "Spec"}, - State: types.SpecStatePassed, - } - }) - - It("should make its address available", func() { - Ω(server.Address()).Should(MatchRegexp(`http://127.0.0.1:\d{2,}`)) - }) - - Describe("/SpecSuiteWillBegin", func() { - It("should decode and forward the Ginkgo config and suite summary", func(done Done) { - forwardingReporter.SpecSuiteWillBegin(config.GinkgoConfig, suiteSummary) - Ω(reporterA.Config).Should(Equal(config.GinkgoConfig)) - Ω(reporterB.Config).Should(Equal(config.GinkgoConfig)) - Ω(reporterA.BeginSummary).Should(Equal(suiteSummary)) - Ω(reporterB.BeginSummary).Should(Equal(suiteSummary)) - close(done) - }) - }) - - Describe("/BeforeSuiteDidRun", func() { - It("should decode and forward the setup summary", func() { - forwardingReporter.BeforeSuiteDidRun(setupSummary) - Ω(reporterA.BeforeSuiteSummary).Should(Equal(setupSummary)) - Ω(reporterB.BeforeSuiteSummary).Should(Equal(setupSummary)) - }) - }) - - Describe("/AfterSuiteDidRun", func() { - It("should decode and forward the setup summary", func() { - forwardingReporter.AfterSuiteDidRun(setupSummary) - Ω(reporterA.AfterSuiteSummary).Should(Equal(setupSummary)) - Ω(reporterB.AfterSuiteSummary).Should(Equal(setupSummary)) - }) - }) - - Describe("/SpecWillRun", func() { - It("should decode and forward the spec summary", func(done Done) { - forwardingReporter.SpecWillRun(specSummary) - Ω(reporterA.SpecWillRunSummaries[0]).Should(Equal(specSummary)) - Ω(reporterB.SpecWillRunSummaries[0]).Should(Equal(specSummary)) - close(done) - }) - }) - - Describe("/SpecDidComplete", func() { - It("should decode and forward the spec summary", func(done Done) { - forwardingReporter.SpecDidComplete(specSummary) - Ω(reporterA.SpecSummaries[0]).Should(Equal(specSummary)) - Ω(reporterB.SpecSummaries[0]).Should(Equal(specSummary)) - close(done) - }) - }) - - Describe("/SpecSuiteDidEnd", func() { - It("should decode and forward the suite summary", func(done Done) { - forwardingReporter.SpecSuiteDidEnd(suiteSummary) - Ω(reporterA.EndSummary).Should(Equal(suiteSummary)) - Ω(reporterB.EndSummary).Should(Equal(suiteSummary)) - close(done) - }) - }) - }) - - Describe("Synchronization endpoints", func() { - Describe("GETting and POSTing BeforeSuiteState", func() { - getBeforeSuite := func() types.RemoteBeforeSuiteData { - resp, err := http.Get(server.Address() + "/BeforeSuiteState") - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - - r := types.RemoteBeforeSuiteData{} - decoder := json.NewDecoder(resp.Body) - err = decoder.Decode(&r) - Ω(err).ShouldNot(HaveOccurred()) - - return r - } - - postBeforeSuite := func(r types.RemoteBeforeSuiteData) { - resp, err := http.Post(server.Address()+"/BeforeSuiteState", "application/json", bytes.NewReader(r.ToJSON())) - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - } - - Context("when the first node's Alive has not been registered yet", func() { - It("should return pending", func() { - state := getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - - state = getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - }) - }) - - Context("when the first node is Alive but has not responded yet", func() { - BeforeEach(func() { - server.RegisterAlive(1, func() bool { - return true - }) - }) - - It("should return pending", func() { - state := getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - - state = getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - }) - }) - - Context("when the first node has responded", func() { - var state types.RemoteBeforeSuiteData - BeforeEach(func() { - server.RegisterAlive(1, func() bool { - return false - }) - - state = types.RemoteBeforeSuiteData{ - Data: []byte("my data"), - State: types.RemoteBeforeSuiteStatePassed, - } - postBeforeSuite(state) - }) - - It("should return the passed in state", func() { - returnedState := getBeforeSuite() - Ω(returnedState).Should(Equal(state)) - }) - }) - - Context("when the first node is no longer Alive and has not responded yet", func() { - BeforeEach(func() { - server.RegisterAlive(1, func() bool { - return false - }) - }) - - It("should return disappeared", func() { - state := getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStateDisappeared})) - - state = getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStateDisappeared})) - }) - }) - }) - - Describe("GETting RemoteAfterSuiteData", func() { - getRemoteAfterSuiteData := func() bool { - resp, err := http.Get(server.Address() + "/RemoteAfterSuiteData") - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - - a := types.RemoteAfterSuiteData{} - decoder := json.NewDecoder(resp.Body) - err = decoder.Decode(&a) - Ω(err).ShouldNot(HaveOccurred()) - - return a.CanRun - } - - Context("when there are unregistered nodes", func() { - BeforeEach(func() { - server.RegisterAlive(2, func() bool { - return false - }) - }) - - It("should return false", func() { - Ω(getRemoteAfterSuiteData()).Should(BeFalse()) - }) - }) - - Context("when all none-node-1 nodes are still running", func() { - BeforeEach(func() { - server.RegisterAlive(2, func() bool { - return true - }) - - server.RegisterAlive(3, func() bool { - return false - }) - }) - - It("should return false", func() { - Ω(getRemoteAfterSuiteData()).Should(BeFalse()) - }) - }) - - Context("when all none-1 nodes are done", func() { - BeforeEach(func() { - server.RegisterAlive(2, func() bool { - return false - }) - - server.RegisterAlive(3, func() bool { - return false - }) - }) - - It("should return true", func() { - Ω(getRemoteAfterSuiteData()).Should(BeTrue()) - }) - - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/index_computer.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/index_computer.go deleted file mode 100644 index 5a67fc7..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/index_computer.go +++ /dev/null @@ -1,55 +0,0 @@ -package spec - -func ParallelizedIndexRange(length int, parallelTotal int, parallelNode int) (startIndex int, count int) { - if length == 0 { - return 0, 0 - } - - // We have more nodes than tests. Trivial case. - if parallelTotal >= length { - if parallelNode > length { - return 0, 0 - } else { - return parallelNode - 1, 1 - } - } - - // This is the minimum amount of tests that a node will be required to run - minTestsPerNode := length / parallelTotal - - // This is the maximum amount of tests that a node will be required to run - // The algorithm guarantees that this would be equal to at least the minimum amount - // and at most one more - maxTestsPerNode := minTestsPerNode - if length%parallelTotal != 0 { - maxTestsPerNode++ - } - - // Number of nodes that will have to run the maximum amount of tests per node - numMaxLoadNodes := length % parallelTotal - - // Number of nodes that precede the current node and will have to run the maximum amount of tests per node - var numPrecedingMaxLoadNodes int - if parallelNode > numMaxLoadNodes { - numPrecedingMaxLoadNodes = numMaxLoadNodes - } else { - numPrecedingMaxLoadNodes = parallelNode - 1 - } - - // Number of nodes that precede the current node and will have to run the minimum amount of tests per node - var numPrecedingMinLoadNodes int - if parallelNode <= numMaxLoadNodes { - numPrecedingMinLoadNodes = 0 - } else { - numPrecedingMinLoadNodes = parallelNode - numMaxLoadNodes - 1 - } - - // Evaluate the test start index and number of tests to run - startIndex = numPrecedingMaxLoadNodes*maxTestsPerNode + numPrecedingMinLoadNodes*minTestsPerNode - if parallelNode > numMaxLoadNodes { - count = minTestsPerNode - } else { - count = maxTestsPerNode - } - return -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/index_computer_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/index_computer_test.go deleted file mode 100644 index 0396d7b..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/index_computer_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package spec_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/spec" - . "github.com/onsi/gomega" -) - -var _ = Describe("ParallelizedIndexRange", func() { - var startIndex, count int - - It("should return the correct index range for 4 tests on 2 nodes", func() { - startIndex, count = ParallelizedIndexRange(4, 2, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(4, 2, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(2)) - }) - - It("should return the correct index range for 5 tests on 2 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 2, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(3)) - - startIndex, count = ParallelizedIndexRange(5, 2, 2) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(2)) - }) - - It("should return the correct index range for 5 tests on 3 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 3, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(5, 3, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(5, 3, 3) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - }) - - It("should return the correct index range for 5 tests on 4 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 4, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(5, 4, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 4, 3) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 4, 4) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - }) - - It("should return the correct index range for 5 tests on 5 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 5, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 2) - Ω(startIndex).Should(Equal(1)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 3) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 4) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 5) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - }) - - It("should return the correct index range for 5 tests on 6 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 6, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 2) - Ω(startIndex).Should(Equal(1)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 3) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 4) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 5) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 6) - Ω(count).Should(Equal(0)) - }) - - It("should return the correct index range for 5 tests on 7 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 7, 6) - Ω(count).Should(Equal(0)) - - startIndex, count = ParallelizedIndexRange(5, 7, 7) - Ω(count).Should(Equal(0)) - }) - - It("should return the correct index range for 11 tests on 7 nodes", func() { - startIndex, count = ParallelizedIndexRange(11, 7, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 3) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 4) - Ω(startIndex).Should(Equal(6)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 5) - Ω(startIndex).Should(Equal(8)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(11, 7, 6) - Ω(startIndex).Should(Equal(9)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(11, 7, 7) - Ω(startIndex).Should(Equal(10)) - Ω(count).Should(Equal(1)) - }) - -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec.go deleted file mode 100644 index ef788b7..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec.go +++ /dev/null @@ -1,197 +0,0 @@ -package spec - -import ( - "fmt" - "io" - "time" - - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -type Spec struct { - subject leafnodes.SubjectNode - focused bool - announceProgress bool - - containers []*containernode.ContainerNode - - state types.SpecState - runTime time.Duration - failure types.SpecFailure -} - -func New(subject leafnodes.SubjectNode, containers []*containernode.ContainerNode, announceProgress bool) *Spec { - spec := &Spec{ - subject: subject, - containers: containers, - focused: subject.Flag() == types.FlagTypeFocused, - announceProgress: announceProgress, - } - - spec.processFlag(subject.Flag()) - for i := len(containers) - 1; i >= 0; i-- { - spec.processFlag(containers[i].Flag()) - } - - return spec -} - -func (spec *Spec) processFlag(flag types.FlagType) { - if flag == types.FlagTypeFocused { - spec.focused = true - } else if flag == types.FlagTypePending { - spec.state = types.SpecStatePending - } -} - -func (spec *Spec) Skip() { - spec.state = types.SpecStateSkipped -} - -func (spec *Spec) Failed() bool { - return spec.state == types.SpecStateFailed || spec.state == types.SpecStatePanicked || spec.state == types.SpecStateTimedOut -} - -func (spec *Spec) Passed() bool { - return spec.state == types.SpecStatePassed -} - -func (spec *Spec) Pending() bool { - return spec.state == types.SpecStatePending -} - -func (spec *Spec) Skipped() bool { - return spec.state == types.SpecStateSkipped -} - -func (spec *Spec) Focused() bool { - return spec.focused -} - -func (spec *Spec) IsMeasurement() bool { - return spec.subject.Type() == types.SpecComponentTypeMeasure -} - -func (spec *Spec) Summary(suiteID string) *types.SpecSummary { - componentTexts := make([]string, len(spec.containers)+1) - componentCodeLocations := make([]types.CodeLocation, len(spec.containers)+1) - - for i, container := range spec.containers { - componentTexts[i] = container.Text() - componentCodeLocations[i] = container.CodeLocation() - } - - componentTexts[len(spec.containers)] = spec.subject.Text() - componentCodeLocations[len(spec.containers)] = spec.subject.CodeLocation() - - return &types.SpecSummary{ - IsMeasurement: spec.IsMeasurement(), - NumberOfSamples: spec.subject.Samples(), - ComponentTexts: componentTexts, - ComponentCodeLocations: componentCodeLocations, - State: spec.state, - RunTime: spec.runTime, - Failure: spec.failure, - Measurements: spec.measurementsReport(), - SuiteID: suiteID, - } -} - -func (spec *Spec) ConcatenatedString() string { - s := "" - for _, container := range spec.containers { - s += container.Text() + " " - } - - return s + spec.subject.Text() -} - -func (spec *Spec) Run(writer io.Writer) { - startTime := time.Now() - defer func() { - spec.runTime = time.Since(startTime) - }() - - for sample := 0; sample < spec.subject.Samples(); sample++ { - spec.runSample(sample, writer) - - if spec.state != types.SpecStatePassed { - return - } - } -} - -func (spec *Spec) runSample(sample int, writer io.Writer) { - spec.state = types.SpecStatePassed - spec.failure = types.SpecFailure{} - innerMostContainerIndexToUnwind := -1 - - defer func() { - for i := innerMostContainerIndexToUnwind; i >= 0; i-- { - container := spec.containers[i] - for _, afterEach := range container.SetupNodesOfType(types.SpecComponentTypeAfterEach) { - spec.announceSetupNode(writer, "AfterEach", container, afterEach) - afterEachState, afterEachFailure := afterEach.Run() - if afterEachState != types.SpecStatePassed && spec.state == types.SpecStatePassed { - spec.state = afterEachState - spec.failure = afterEachFailure - } - } - } - }() - - for i, container := range spec.containers { - innerMostContainerIndexToUnwind = i - for _, beforeEach := range container.SetupNodesOfType(types.SpecComponentTypeBeforeEach) { - spec.announceSetupNode(writer, "BeforeEach", container, beforeEach) - spec.state, spec.failure = beforeEach.Run() - if spec.state != types.SpecStatePassed { - return - } - } - } - - for _, container := range spec.containers { - for _, justBeforeEach := range container.SetupNodesOfType(types.SpecComponentTypeJustBeforeEach) { - spec.announceSetupNode(writer, "JustBeforeEach", container, justBeforeEach) - spec.state, spec.failure = justBeforeEach.Run() - if spec.state != types.SpecStatePassed { - return - } - } - } - - spec.announceSubject(writer, spec.subject) - spec.state, spec.failure = spec.subject.Run() -} - -func (spec *Spec) announceSetupNode(writer io.Writer, nodeType string, container *containernode.ContainerNode, setupNode leafnodes.BasicNode) { - if spec.announceProgress { - s := fmt.Sprintf("[%s] %s\n %s\n", nodeType, container.Text(), setupNode.CodeLocation().String()) - writer.Write([]byte(s)) - } -} - -func (spec *Spec) announceSubject(writer io.Writer, subject leafnodes.SubjectNode) { - if spec.announceProgress { - nodeType := "" - switch subject.Type() { - case types.SpecComponentTypeIt: - nodeType = "It" - case types.SpecComponentTypeMeasure: - nodeType = "Measure" - } - s := fmt.Sprintf("[%s] %s\n %s\n", nodeType, subject.Text(), subject.CodeLocation().String()) - writer.Write([]byte(s)) - } -} - -func (spec *Spec) measurementsReport() map[string]*types.SpecMeasurement { - if !spec.IsMeasurement() || spec.Failed() { - return map[string]*types.SpecMeasurement{} - } - - return spec.subject.(*leafnodes.MeasureNode).MeasurementsReport() -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go deleted file mode 100644 index 8681a72..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package spec_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestSpec(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Spec Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_test.go deleted file mode 100644 index 6d0f58c..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_test.go +++ /dev/null @@ -1,626 +0,0 @@ -package spec_test - -import ( - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - - . "github.com/onsi/ginkgo/internal/spec" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -var noneFlag = types.FlagTypeNone -var focusedFlag = types.FlagTypeFocused -var pendingFlag = types.FlagTypePending - -var _ = Describe("Spec", func() { - var ( - failer *Failer.Failer - codeLocation types.CodeLocation - nodesThatRan []string - spec *Spec - buffer *gbytes.Buffer - ) - - newBody := func(text string, fail bool) func() { - return func() { - nodesThatRan = append(nodesThatRan, text) - if fail { - failer.Fail(text, codeLocation) - } - } - } - - newIt := func(text string, flag types.FlagType, fail bool) *leafnodes.ItNode { - return leafnodes.NewItNode(text, newBody(text, fail), flag, codeLocation, 0, failer, 0) - } - - newItWithBody := func(text string, body interface{}) *leafnodes.ItNode { - return leafnodes.NewItNode(text, body, noneFlag, codeLocation, 0, failer, 0) - } - - newMeasure := func(text string, flag types.FlagType, fail bool, samples int) *leafnodes.MeasureNode { - return leafnodes.NewMeasureNode(text, func(Benchmarker) { - nodesThatRan = append(nodesThatRan, text) - if fail { - failer.Fail(text, codeLocation) - } - }, flag, codeLocation, samples, failer, 0) - } - - newBef := func(text string, fail bool) leafnodes.BasicNode { - return leafnodes.NewBeforeEachNode(newBody(text, fail), codeLocation, 0, failer, 0) - } - - newAft := func(text string, fail bool) leafnodes.BasicNode { - return leafnodes.NewAfterEachNode(newBody(text, fail), codeLocation, 0, failer, 0) - } - - newJusBef := func(text string, fail bool) leafnodes.BasicNode { - return leafnodes.NewJustBeforeEachNode(newBody(text, fail), codeLocation, 0, failer, 0) - } - - newContainer := func(text string, flag types.FlagType, setupNodes ...leafnodes.BasicNode) *containernode.ContainerNode { - c := containernode.New(text, flag, codeLocation) - for _, node := range setupNodes { - c.PushSetupNode(node) - } - return c - } - - containers := func(containers ...*containernode.ContainerNode) []*containernode.ContainerNode { - return containers - } - - BeforeEach(func() { - buffer = gbytes.NewBuffer() - failer = Failer.New() - codeLocation = codelocation.New(0) - nodesThatRan = []string{} - }) - - Describe("marking specs focused and pending", func() { - It("should satisfy various caes", func() { - cases := []struct { - ContainerFlags []types.FlagType - SubjectFlag types.FlagType - Pending bool - Focused bool - }{ - {[]types.FlagType{}, noneFlag, false, false}, - {[]types.FlagType{}, focusedFlag, false, true}, - {[]types.FlagType{}, pendingFlag, true, false}, - {[]types.FlagType{noneFlag}, noneFlag, false, false}, - {[]types.FlagType{focusedFlag}, noneFlag, false, true}, - {[]types.FlagType{pendingFlag}, noneFlag, true, false}, - {[]types.FlagType{noneFlag}, focusedFlag, false, true}, - {[]types.FlagType{focusedFlag}, focusedFlag, false, true}, - {[]types.FlagType{pendingFlag}, focusedFlag, true, true}, - {[]types.FlagType{noneFlag}, pendingFlag, true, false}, - {[]types.FlagType{focusedFlag}, pendingFlag, true, true}, - {[]types.FlagType{pendingFlag}, pendingFlag, true, false}, - {[]types.FlagType{focusedFlag, noneFlag}, noneFlag, false, true}, - {[]types.FlagType{noneFlag, focusedFlag}, noneFlag, false, true}, - {[]types.FlagType{pendingFlag, noneFlag}, noneFlag, true, false}, - {[]types.FlagType{noneFlag, pendingFlag}, noneFlag, true, false}, - {[]types.FlagType{focusedFlag, pendingFlag}, noneFlag, true, true}, - } - - for i, c := range cases { - subject := newIt("it node", c.SubjectFlag, false) - containers := []*containernode.ContainerNode{} - for _, flag := range c.ContainerFlags { - containers = append(containers, newContainer("container", flag)) - } - - spec := New(subject, containers, false) - Ω(spec.Pending()).Should(Equal(c.Pending), "Case %d: %#v", i, c) - Ω(spec.Focused()).Should(Equal(c.Focused), "Case %d: %#v", i, c) - - if c.Pending { - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePending)) - } - } - }) - }) - - Describe("Skip", func() { - It("should be skipped", func() { - spec := New(newIt("it node", noneFlag, false), containers(newContainer("container", noneFlag)), false) - Ω(spec.Skipped()).Should(BeFalse()) - spec.Skip() - Ω(spec.Skipped()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateSkipped)) - }) - }) - - Describe("IsMeasurement", func() { - It("should be true if the subject is a measurement node", func() { - spec := New(newIt("it node", noneFlag, false), containers(newContainer("container", noneFlag)), false) - Ω(spec.IsMeasurement()).Should(BeFalse()) - Ω(spec.Summary("").IsMeasurement).Should(BeFalse()) - Ω(spec.Summary("").NumberOfSamples).Should(Equal(1)) - - spec = New(newMeasure("measure node", noneFlag, false, 10), containers(newContainer("container", noneFlag)), false) - Ω(spec.IsMeasurement()).Should(BeTrue()) - Ω(spec.Summary("").IsMeasurement).Should(BeTrue()) - Ω(spec.Summary("").NumberOfSamples).Should(Equal(10)) - }) - }) - - Describe("Passed", func() { - It("should pass when the subject passed", func() { - spec := New(newIt("it node", noneFlag, false), containers(), false) - spec.Run(buffer) - - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePassed)) - Ω(spec.Summary("").Failure).Should(BeZero()) - }) - }) - - Describe("Failed", func() { - It("should be failed if the failure was panic", func() { - spec := New(newItWithBody("panicky it", func() { - panic("bam") - }), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePanicked)) - Ω(spec.Summary("").Failure.Message).Should(Equal("Test Panicked")) - Ω(spec.Summary("").Failure.ForwardedPanic).Should(Equal("bam")) - }) - - It("should be failed if the failure was a timeout", func() { - spec := New(newItWithBody("sleepy it", func(done Done) {}), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateTimedOut)) - Ω(spec.Summary("").Failure.Message).Should(Equal("Timed out")) - }) - - It("should be failed if the failure was... a failure", func() { - spec := New(newItWithBody("failing it", func() { - failer.Fail("bam", codeLocation) - }), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateFailed)) - Ω(spec.Summary("").Failure.Message).Should(Equal("bam")) - }) - }) - - Describe("Concatenated string", func() { - It("should concatenate the texts of the containers and the subject", func() { - spec := New( - newIt("it node", noneFlag, false), - containers( - newContainer("outer container", noneFlag), - newContainer("inner container", noneFlag), - ), - false, - ) - - Ω(spec.ConcatenatedString()).Should(Equal("outer container inner container it node")) - }) - }) - - Describe("running it specs", func() { - Context("with just an it", func() { - Context("that succeeds", func() { - It("should run the it and report on its success", func() { - spec := New(newIt("it node", noneFlag, false), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(nodesThatRan).Should(Equal([]string{"it node"})) - }) - }) - - Context("that fails", func() { - It("should run the it and report on its success", func() { - spec := New(newIt("it node", noneFlag, true), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").Failure.Message).Should(Equal("it node")) - Ω(nodesThatRan).Should(Equal([]string{"it node"})) - }) - }) - }) - - Context("with a full set of setup nodes", func() { - var failingNodes map[string]bool - - BeforeEach(func() { - failingNodes = map[string]bool{} - }) - - JustBeforeEach(func() { - spec = New( - newIt("it node", noneFlag, failingNodes["it node"]), - containers( - newContainer("outer container", noneFlag, - newBef("outer bef A", failingNodes["outer bef A"]), - newBef("outer bef B", failingNodes["outer bef B"]), - newJusBef("outer jusbef A", failingNodes["outer jusbef A"]), - newJusBef("outer jusbef B", failingNodes["outer jusbef B"]), - newAft("outer aft A", failingNodes["outer aft A"]), - newAft("outer aft B", failingNodes["outer aft B"]), - ), - newContainer("inner container", noneFlag, - newBef("inner bef A", failingNodes["inner bef A"]), - newBef("inner bef B", failingNodes["inner bef B"]), - newJusBef("inner jusbef A", failingNodes["inner jusbef A"]), - newJusBef("inner jusbef B", failingNodes["inner jusbef B"]), - newAft("inner aft A", failingNodes["inner aft A"]), - newAft("inner aft B", failingNodes["inner aft B"]), - ), - ), - false, - ) - spec.Run(buffer) - }) - - Context("that all pass", func() { - It("should walk through the nodes in the correct order", func() { - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - }) - }) - - Context("when the subject fails", func() { - BeforeEach(func() { - failingNodes["it node"] = true - }) - - It("should run the afters", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("it node")) - }) - }) - - Context("when an inner before fails", func() { - BeforeEach(func() { - failingNodes["inner bef A"] = true - }) - - It("should not run any other befores, but it should run the subsequent afters", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("inner bef A")) - }) - }) - - Context("when an outer before fails", func() { - BeforeEach(func() { - failingNodes["outer bef B"] = true - }) - - It("should not run any other befores, but it should run the subsequent afters", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("outer bef B")) - }) - }) - - Context("when an after fails", func() { - BeforeEach(func() { - failingNodes["inner aft B"] = true - }) - - It("should run all other afters, but mark the test as failed", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("inner aft B")) - }) - }) - - Context("when a just before each fails", func() { - BeforeEach(func() { - failingNodes["outer jusbef B"] = true - }) - - It("should run the afters, but not the subject", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("outer jusbef B")) - }) - }) - - Context("when an after fails after an earlier node has failed", func() { - BeforeEach(func() { - failingNodes["it node"] = true - failingNodes["inner aft B"] = true - }) - - It("should record the earlier failure", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("it node")) - }) - }) - }) - }) - - Describe("running measurement specs", func() { - Context("when the measurement succeeds", func() { - It("should run N samples", func() { - spec = New( - newMeasure("measure node", noneFlag, false, 3), - containers( - newContainer("container", noneFlag, - newBef("bef A", false), - newJusBef("jusbef A", false), - newAft("aft A", false), - ), - ), - false, - ) - spec.Run(buffer) - - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(nodesThatRan).Should(Equal([]string{ - "bef A", - "jusbef A", - "measure node", - "aft A", - "bef A", - "jusbef A", - "measure node", - "aft A", - "bef A", - "jusbef A", - "measure node", - "aft A", - })) - }) - }) - - Context("when the measurement fails", func() { - It("should bail after the failure occurs", func() { - spec = New( - newMeasure("measure node", noneFlag, true, 3), - containers( - newContainer("container", noneFlag, - newBef("bef A", false), - newJusBef("jusbef A", false), - newAft("aft A", false), - ), - ), - false, - ) - spec.Run(buffer) - - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "bef A", - "jusbef A", - "measure node", - "aft A", - })) - }) - }) - }) - - Describe("Summary", func() { - var ( - subjectCodeLocation types.CodeLocation - outerContainerCodeLocation types.CodeLocation - innerContainerCodeLocation types.CodeLocation - summary *types.SpecSummary - ) - - BeforeEach(func() { - subjectCodeLocation = codelocation.New(0) - outerContainerCodeLocation = codelocation.New(0) - innerContainerCodeLocation = codelocation.New(0) - - spec = New( - leafnodes.NewItNode("it node", func() { - time.Sleep(10 * time.Millisecond) - }, noneFlag, subjectCodeLocation, 0, failer, 0), - containers( - containernode.New("outer container", noneFlag, outerContainerCodeLocation), - containernode.New("inner container", noneFlag, innerContainerCodeLocation), - ), - false, - ) - - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - summary = spec.Summary("suite id") - }) - - It("should have the suite id", func() { - Ω(summary.SuiteID).Should(Equal("suite id")) - }) - - It("should have the component texts and code locations", func() { - Ω(summary.ComponentTexts).Should(Equal([]string{"outer container", "inner container", "it node"})) - Ω(summary.ComponentCodeLocations).Should(Equal([]types.CodeLocation{outerContainerCodeLocation, innerContainerCodeLocation, subjectCodeLocation})) - }) - - It("should have a runtime", func() { - Ω(summary.RunTime).Should(BeNumerically(">=", 10*time.Millisecond)) - }) - - It("should not be a measurement, or have a measurement summary", func() { - Ω(summary.IsMeasurement).Should(BeFalse()) - Ω(summary.Measurements).Should(BeEmpty()) - }) - }) - - Describe("Summaries for measurements", func() { - var summary *types.SpecSummary - - BeforeEach(func() { - spec = New(leafnodes.NewMeasureNode("measure node", func(b Benchmarker) { - b.RecordValue("a value", 7, "some info") - }, noneFlag, codeLocation, 4, failer, 0), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - summary = spec.Summary("suite id") - }) - - It("should include the number of samples", func() { - Ω(summary.NumberOfSamples).Should(Equal(4)) - }) - - It("should be a measurement", func() { - Ω(summary.IsMeasurement).Should(BeTrue()) - }) - - It("should have the measurements report", func() { - Ω(summary.Measurements).Should(HaveKey("a value")) - - report := summary.Measurements["a value"] - Ω(report.Name).Should(Equal("a value")) - Ω(report.Info).Should(Equal("some info")) - Ω(report.Results).Should(Equal([]float64{7, 7, 7, 7})) - }) - }) - - Describe("When told to emit progress", func() { - It("should emit progress to the writer as it runs Befores, JustBefores, Afters, and Its", func() { - spec = New( - newIt("it node", noneFlag, false), - containers( - newContainer("outer container", noneFlag, - newBef("outer bef A", false), - newJusBef("outer jusbef A", false), - newAft("outer aft A", false), - ), - newContainer("inner container", noneFlag, - newBef("inner bef A", false), - newJusBef("inner jusbef A", false), - newAft("inner aft A", false), - ), - ), - true, - ) - spec.Run(buffer) - - Ω(buffer).Should(gbytes.Say(`\[BeforeEach\] outer container`)) - Ω(buffer).Should(gbytes.Say(`\[BeforeEach\] inner container`)) - Ω(buffer).Should(gbytes.Say(`\[JustBeforeEach\] outer container`)) - Ω(buffer).Should(gbytes.Say(`\[JustBeforeEach\] inner container`)) - Ω(buffer).Should(gbytes.Say(`\[It\] it node`)) - Ω(buffer).Should(gbytes.Say(`\[AfterEach\] inner container`)) - Ω(buffer).Should(gbytes.Say(`\[AfterEach\] outer container`)) - }) - - It("should emit progress to the writer as it runs Befores, JustBefores, Afters, and Measures", func() { - spec = New( - newMeasure("measure node", noneFlag, false, 2), - containers(), - true, - ) - spec.Run(buffer) - - Ω(buffer).Should(gbytes.Say(`\[Measure\] measure node`)) - Ω(buffer).Should(gbytes.Say(`\[Measure\] measure node`)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/specs.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/specs.go deleted file mode 100644 index 9c671e3..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/specs.go +++ /dev/null @@ -1,122 +0,0 @@ -package spec - -import ( - "math/rand" - "regexp" - "sort" -) - -type Specs struct { - specs []*Spec - numberOfOriginalSpecs int - hasProgrammaticFocus bool -} - -func NewSpecs(specs []*Spec) *Specs { - return &Specs{ - specs: specs, - numberOfOriginalSpecs: len(specs), - } -} - -func (e *Specs) Specs() []*Spec { - return e.specs -} - -func (e *Specs) NumberOfOriginalSpecs() int { - return e.numberOfOriginalSpecs -} - -func (e *Specs) HasProgrammaticFocus() bool { - return e.hasProgrammaticFocus -} - -func (e *Specs) Shuffle(r *rand.Rand) { - sort.Sort(e) - permutation := r.Perm(len(e.specs)) - shuffledSpecs := make([]*Spec, len(e.specs)) - for i, j := range permutation { - shuffledSpecs[i] = e.specs[j] - } - e.specs = shuffledSpecs -} - -func (e *Specs) ApplyFocus(description string, focusString string, skipString string) { - if focusString == "" && skipString == "" { - e.applyProgrammaticFocus() - } else { - e.applyRegExpFocus(description, focusString, skipString) - } -} - -func (e *Specs) applyProgrammaticFocus() { - e.hasProgrammaticFocus = false - for _, spec := range e.specs { - if spec.Focused() && !spec.Pending() { - e.hasProgrammaticFocus = true - break - } - } - - if e.hasProgrammaticFocus { - for _, spec := range e.specs { - if !spec.Focused() { - spec.Skip() - } - } - } -} - -func (e *Specs) applyRegExpFocus(description string, focusString string, skipString string) { - for _, spec := range e.specs { - matchesFocus := true - matchesSkip := false - - toMatch := []byte(description + " " + spec.ConcatenatedString()) - - if focusString != "" { - focusFilter := regexp.MustCompile(focusString) - matchesFocus = focusFilter.Match([]byte(toMatch)) - } - - if skipString != "" { - skipFilter := regexp.MustCompile(skipString) - matchesSkip = skipFilter.Match([]byte(toMatch)) - } - - if !matchesFocus || matchesSkip { - spec.Skip() - } - } -} - -func (e *Specs) SkipMeasurements() { - for _, spec := range e.specs { - if spec.IsMeasurement() { - spec.Skip() - } - } -} - -func (e *Specs) TrimForParallelization(total int, node int) { - startIndex, count := ParallelizedIndexRange(len(e.specs), total, node) - if count == 0 { - e.specs = make([]*Spec, 0) - } else { - e.specs = e.specs[startIndex : startIndex+count] - } -} - -//sort.Interface - -func (e *Specs) Len() int { - return len(e.specs) -} - -func (e *Specs) Less(i, j int) bool { - return e.specs[i].ConcatenatedString() < e.specs[j].ConcatenatedString() -} - -func (e *Specs) Swap(i, j int) { - e.specs[i], e.specs[j] = e.specs[j], e.specs[i] -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/specs_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/specs_test.go deleted file mode 100644 index ce9f5f3..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/specs_test.go +++ /dev/null @@ -1,335 +0,0 @@ -package spec_test - -import ( - "math/rand" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/spec" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Specs", func() { - var specs *Specs - - newSpec := func(text string, flag types.FlagType) *Spec { - subject := leafnodes.NewItNode(text, func() {}, flag, codelocation.New(0), 0, nil, 0) - return New(subject, []*containernode.ContainerNode{}, false) - } - - newMeasureSpec := func(text string, flag types.FlagType) *Spec { - subject := leafnodes.NewMeasureNode(text, func(Benchmarker) {}, flag, codelocation.New(0), 0, nil, 0) - return New(subject, []*containernode.ContainerNode{}, false) - } - - newSpecs := func(args ...interface{}) *Specs { - specs := []*Spec{} - for index := 0; index < len(args)-1; index += 2 { - specs = append(specs, newSpec(args[index].(string), args[index+1].(types.FlagType))) - } - return NewSpecs(specs) - } - - specTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - texts = append(texts, spec.ConcatenatedString()) - } - return texts - } - - willRunTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - if !(spec.Skipped() || spec.Pending()) { - texts = append(texts, spec.ConcatenatedString()) - } - } - return texts - } - - skippedTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - if spec.Skipped() { - texts = append(texts, spec.ConcatenatedString()) - } - } - return texts - } - - pendingTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - if spec.Pending() { - texts = append(texts, spec.ConcatenatedString()) - } - } - return texts - } - - Describe("Shuffling specs", func() { - It("should shuffle the specs using the passed in randomizer", func() { - specs17 := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - specs17.Shuffle(rand.New(rand.NewSource(17))) - texts17 := specTexts(specs17) - - specs17Again := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - specs17Again.Shuffle(rand.New(rand.NewSource(17))) - texts17Again := specTexts(specs17Again) - - specs15 := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - specs15.Shuffle(rand.New(rand.NewSource(15))) - texts15 := specTexts(specs15) - - specsUnshuffled := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - textsUnshuffled := specTexts(specsUnshuffled) - - Ω(textsUnshuffled).Should(Equal([]string{"C", "A", "B"})) - - Ω(texts17).Should(Equal(texts17Again)) - Ω(texts17).ShouldNot(Equal(texts15)) - Ω(texts17).ShouldNot(Equal(textsUnshuffled)) - Ω(texts15).ShouldNot(Equal(textsUnshuffled)) - - Ω(texts17).Should(HaveLen(3)) - Ω(texts17).Should(ContainElement("A")) - Ω(texts17).Should(ContainElement("B")) - Ω(texts17).Should(ContainElement("C")) - - Ω(texts15).Should(HaveLen(3)) - Ω(texts15).Should(ContainElement("A")) - Ω(texts15).Should(ContainElement("B")) - Ω(texts15).Should(ContainElement("C")) - }) - }) - - Describe("with no programmatic focus", func() { - BeforeEach(func() { - specs = newSpecs("A1", noneFlag, "A2", noneFlag, "B1", noneFlag, "B2", pendingFlag) - specs.ApplyFocus("", "", "") - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - - Describe("Applying focus/skip", func() { - var description, focusString, skipString string - - BeforeEach(func() { - description, focusString, skipString = "", "", "" - }) - - JustBeforeEach(func() { - specs = newSpecs("A1", focusedFlag, "A2", noneFlag, "B1", focusedFlag, "B2", pendingFlag) - specs.ApplyFocus(description, focusString, skipString) - }) - - Context("with neither a focus string nor a skip string", func() { - It("should apply the programmatic focus", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1", "B1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A2", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - - It("should report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeTrue()) - }) - }) - - Context("with a focus regexp", func() { - BeforeEach(func() { - focusString = "A" - }) - - It("should override the programmatic focus", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1", "A2"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"B1", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - - Context("with a focus regexp", func() { - BeforeEach(func() { - focusString = "B" - }) - - It("should not override any pendings", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"B1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A1", "A2"})) - Ω(pendingTexts(specs)).Should(Equal([]string{"B2"})) - }) - }) - - Context("with a description", func() { - BeforeEach(func() { - description = "C" - focusString = "C" - }) - - It("should include the description in the focus determination", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1", "A2", "B1"})) - Ω(skippedTexts(specs)).Should(BeEmpty()) - Ω(pendingTexts(specs)).Should(Equal([]string{"B2"})) - }) - }) - - Context("with a description", func() { - BeforeEach(func() { - description = "C" - skipString = "C" - }) - - It("should include the description in the focus determination", func() { - Ω(willRunTexts(specs)).Should(BeEmpty()) - Ω(skippedTexts(specs)).Should(Equal([]string{"A1", "A2", "B1", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - }) - - Context("with a skip regexp", func() { - BeforeEach(func() { - skipString = "A" - }) - - It("should override the programmatic focus", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"B1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A1", "A2"})) - Ω(pendingTexts(specs)).Should(Equal([]string{"B2"})) - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - - Context("with both a focus and a skip regexp", func() { - BeforeEach(func() { - focusString = "1" - skipString = "B" - }) - - It("should AND the two", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A2", "B1", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - }) - - Describe("With a focused spec within a pending context and a pending spec within a focused context", func() { - BeforeEach(func() { - pendingInFocused := New( - leafnodes.NewItNode("PendingInFocused", func() {}, pendingFlag, codelocation.New(0), 0, nil, 0), - []*containernode.ContainerNode{ - containernode.New("", focusedFlag, codelocation.New(0)), - }, false) - - focusedInPending := New( - leafnodes.NewItNode("FocusedInPending", func() {}, focusedFlag, codelocation.New(0), 0, nil, 0), - []*containernode.ContainerNode{ - containernode.New("", pendingFlag, codelocation.New(0)), - }, false) - - specs = NewSpecs([]*Spec{ - newSpec("A", noneFlag), - newSpec("B", noneFlag), - pendingInFocused, - focusedInPending, - }) - specs.ApplyFocus("", "", "") - }) - - It("should not have a programmatic focus and should run all tests", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A", "B"})) - Ω(skippedTexts(specs)).Should(BeEmpty()) - Ω(pendingTexts(specs)).Should(ConsistOf(ContainSubstring("PendingInFocused"), ContainSubstring("FocusedInPending"))) - }) - }) - - Describe("skipping measurements", func() { - BeforeEach(func() { - specs = NewSpecs([]*Spec{ - newSpec("A", noneFlag), - newSpec("B", noneFlag), - newSpec("C", pendingFlag), - newMeasureSpec("measurementA", noneFlag), - newMeasureSpec("measurementB", pendingFlag), - }) - }) - - It("should skip measurements", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A", "B", "measurementA"})) - Ω(skippedTexts(specs)).Should(BeEmpty()) - Ω(pendingTexts(specs)).Should(Equal([]string{"C", "measurementB"})) - - specs.SkipMeasurements() - - Ω(willRunTexts(specs)).Should(Equal([]string{"A", "B"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"measurementA", "measurementB"})) - Ω(pendingTexts(specs)).Should(Equal([]string{"C"})) - }) - }) - - Describe("when running tests in parallel", func() { - It("should select out a subset of the tests", func() { - specsNode1 := newSpecs("A", noneFlag, "B", noneFlag, "C", noneFlag, "D", noneFlag, "E", noneFlag) - specsNode2 := newSpecs("A", noneFlag, "B", noneFlag, "C", noneFlag, "D", noneFlag, "E", noneFlag) - specsNode3 := newSpecs("A", noneFlag, "B", noneFlag, "C", noneFlag, "D", noneFlag, "E", noneFlag) - - specsNode1.TrimForParallelization(3, 1) - specsNode2.TrimForParallelization(3, 2) - specsNode3.TrimForParallelization(3, 3) - - Ω(willRunTexts(specsNode1)).Should(Equal([]string{"A", "B"})) - Ω(willRunTexts(specsNode2)).Should(Equal([]string{"C", "D"})) - Ω(willRunTexts(specsNode3)).Should(Equal([]string{"E"})) - - Ω(specsNode1.Specs()).Should(HaveLen(2)) - Ω(specsNode2.Specs()).Should(HaveLen(2)) - Ω(specsNode3.Specs()).Should(HaveLen(1)) - - Ω(specsNode1.NumberOfOriginalSpecs()).Should(Equal(5)) - Ω(specsNode2.NumberOfOriginalSpecs()).Should(Equal(5)) - Ω(specsNode3.NumberOfOriginalSpecs()).Should(Equal(5)) - }) - - Context("when way too many nodes are used", func() { - It("should return 0 specs", func() { - specsNode1 := newSpecs("A", noneFlag, "B", noneFlag) - specsNode2 := newSpecs("A", noneFlag, "B", noneFlag) - specsNode3 := newSpecs("A", noneFlag, "B", noneFlag) - - specsNode1.TrimForParallelization(3, 1) - specsNode2.TrimForParallelization(3, 2) - specsNode3.TrimForParallelization(3, 3) - - Ω(willRunTexts(specsNode1)).Should(Equal([]string{"A"})) - Ω(willRunTexts(specsNode2)).Should(Equal([]string{"B"})) - Ω(willRunTexts(specsNode3)).Should(BeEmpty()) - - Ω(specsNode1.Specs()).Should(HaveLen(1)) - Ω(specsNode2.Specs()).Should(HaveLen(1)) - Ω(specsNode3.Specs()).Should(HaveLen(0)) - - Ω(specsNode1.NumberOfOriginalSpecs()).Should(Equal(2)) - Ω(specsNode2.NumberOfOriginalSpecs()).Should(Equal(2)) - Ω(specsNode3.NumberOfOriginalSpecs()).Should(Equal(2)) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/random_id.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/random_id.go deleted file mode 100644 index a0b8b62..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/random_id.go +++ /dev/null @@ -1,15 +0,0 @@ -package specrunner - -import ( - "crypto/rand" - "fmt" -) - -func randomID() string { - b := make([]byte, 8) - _, err := rand.Read(b) - if err != nil { - return "" - } - return fmt.Sprintf("%x-%x-%x-%x", b[0:2], b[2:4], b[4:6], b[6:8]) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go deleted file mode 100644 index 7ca7740..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go +++ /dev/null @@ -1,324 +0,0 @@ -package specrunner - -import ( - "fmt" - "os" - "os/signal" - "sync" - "syscall" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - Writer "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - - "time" -) - -type SpecRunner struct { - description string - beforeSuiteNode leafnodes.SuiteNode - specs *spec.Specs - afterSuiteNode leafnodes.SuiteNode - reporters []reporters.Reporter - startTime time.Time - suiteID string - runningSpec *spec.Spec - writer Writer.WriterInterface - config config.GinkgoConfigType - interrupted bool - lock *sync.Mutex -} - -func New(description string, beforeSuiteNode leafnodes.SuiteNode, specs *spec.Specs, afterSuiteNode leafnodes.SuiteNode, reporters []reporters.Reporter, writer Writer.WriterInterface, config config.GinkgoConfigType) *SpecRunner { - return &SpecRunner{ - description: description, - beforeSuiteNode: beforeSuiteNode, - specs: specs, - afterSuiteNode: afterSuiteNode, - reporters: reporters, - writer: writer, - config: config, - suiteID: randomID(), - lock: &sync.Mutex{}, - } -} - -func (runner *SpecRunner) Run() bool { - if runner.config.DryRun { - runner.performDryRun() - return true - } - - runner.reportSuiteWillBegin() - go runner.registerForInterrupts() - - suitePassed := runner.runBeforeSuite() - - if suitePassed { - suitePassed = runner.runSpecs() - } - - runner.blockForeverIfInterrupted() - - suitePassed = runner.runAfterSuite() && suitePassed - - runner.reportSuiteDidEnd(suitePassed) - - return suitePassed -} - -func (runner *SpecRunner) performDryRun() { - runner.reportSuiteWillBegin() - - if runner.beforeSuiteNode != nil { - summary := runner.beforeSuiteNode.Summary() - summary.State = types.SpecStatePassed - runner.reportBeforeSuite(summary) - } - - for _, spec := range runner.specs.Specs() { - summary := spec.Summary(runner.suiteID) - runner.reportSpecWillRun(summary) - if summary.State == types.SpecStateInvalid { - summary.State = types.SpecStatePassed - } - runner.reportSpecDidComplete(summary, false) - } - - if runner.afterSuiteNode != nil { - summary := runner.afterSuiteNode.Summary() - summary.State = types.SpecStatePassed - runner.reportAfterSuite(summary) - } - - runner.reportSuiteDidEnd(true) -} - -func (runner *SpecRunner) runBeforeSuite() bool { - if runner.beforeSuiteNode == nil || runner.wasInterrupted() { - return true - } - - runner.writer.Truncate() - conf := runner.config - passed := runner.beforeSuiteNode.Run(conf.ParallelNode, conf.ParallelTotal, conf.SyncHost) - if !passed { - runner.writer.DumpOut() - } - runner.reportBeforeSuite(runner.beforeSuiteNode.Summary()) - return passed -} - -func (runner *SpecRunner) runAfterSuite() bool { - if runner.afterSuiteNode == nil { - return true - } - - runner.writer.Truncate() - conf := runner.config - passed := runner.afterSuiteNode.Run(conf.ParallelNode, conf.ParallelTotal, conf.SyncHost) - if !passed { - runner.writer.DumpOut() - } - runner.reportAfterSuite(runner.afterSuiteNode.Summary()) - return passed -} - -func (runner *SpecRunner) runSpecs() bool { - suiteFailed := false - skipRemainingSpecs := false - for _, spec := range runner.specs.Specs() { - if runner.wasInterrupted() { - return suiteFailed - } - if skipRemainingSpecs { - spec.Skip() - } - runner.reportSpecWillRun(spec.Summary(runner.suiteID)) - - if !spec.Skipped() && !spec.Pending() { - runner.runningSpec = spec - spec.Run(runner.writer) - runner.runningSpec = nil - if spec.Failed() { - suiteFailed = true - } - } else if spec.Pending() && runner.config.FailOnPending { - suiteFailed = true - } - - runner.reportSpecDidComplete(spec.Summary(runner.suiteID), spec.Failed()) - - if spec.Failed() && runner.config.FailFast { - skipRemainingSpecs = true - } - } - - return !suiteFailed -} - -func (runner *SpecRunner) CurrentSpecSummary() (*types.SpecSummary, bool) { - if runner.runningSpec == nil { - return nil, false - } - - return runner.runningSpec.Summary(runner.suiteID), true -} - -func (runner *SpecRunner) registerForInterrupts() { - c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt, syscall.SIGTERM) - - <-c - signal.Stop(c) - runner.markInterrupted() - go runner.registerForHardInterrupts() - runner.writer.DumpOutWithHeader(` -Received interrupt. Emitting contents of GinkgoWriter... ---------------------------------------------------------- -`) - if runner.afterSuiteNode != nil { - fmt.Fprint(os.Stderr, ` ---------------------------------------------------------- -Received interrupt. Running AfterSuite... -^C again to terminate immediately -`) - runner.runAfterSuite() - } - runner.reportSuiteDidEnd(false) - os.Exit(1) -} - -func (runner *SpecRunner) registerForHardInterrupts() { - c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt, syscall.SIGTERM) - - <-c - fmt.Fprintln(os.Stderr, "\nReceived second interrupt. Shutting down.") - os.Exit(1) -} - -func (runner *SpecRunner) blockForeverIfInterrupted() { - runner.lock.Lock() - interrupted := runner.interrupted - runner.lock.Unlock() - - if interrupted { - select {} - } -} - -func (runner *SpecRunner) markInterrupted() { - runner.lock.Lock() - defer runner.lock.Unlock() - runner.interrupted = true -} - -func (runner *SpecRunner) wasInterrupted() bool { - runner.lock.Lock() - defer runner.lock.Unlock() - return runner.interrupted -} - -func (runner *SpecRunner) reportSuiteWillBegin() { - runner.startTime = time.Now() - summary := runner.summary(true) - for _, reporter := range runner.reporters { - reporter.SpecSuiteWillBegin(runner.config, summary) - } -} - -func (runner *SpecRunner) reportBeforeSuite(summary *types.SetupSummary) { - for _, reporter := range runner.reporters { - reporter.BeforeSuiteDidRun(summary) - } -} - -func (runner *SpecRunner) reportAfterSuite(summary *types.SetupSummary) { - for _, reporter := range runner.reporters { - reporter.AfterSuiteDidRun(summary) - } -} - -func (runner *SpecRunner) reportSpecWillRun(summary *types.SpecSummary) { - runner.writer.Truncate() - - for _, reporter := range runner.reporters { - reporter.SpecWillRun(summary) - } -} - -func (runner *SpecRunner) reportSpecDidComplete(summary *types.SpecSummary, failed bool) { - for i := len(runner.reporters) - 1; i >= 1; i-- { - runner.reporters[i].SpecDidComplete(summary) - } - - if failed { - runner.writer.DumpOut() - } - - runner.reporters[0].SpecDidComplete(summary) -} - -func (runner *SpecRunner) reportSuiteDidEnd(success bool) { - summary := runner.summary(success) - summary.RunTime = time.Since(runner.startTime) - for _, reporter := range runner.reporters { - reporter.SpecSuiteDidEnd(summary) - } -} - -func (runner *SpecRunner) countSpecsSatisfying(filter func(ex *spec.Spec) bool) (count int) { - count = 0 - - for _, spec := range runner.specs.Specs() { - if filter(spec) { - count++ - } - } - - return count -} - -func (runner *SpecRunner) summary(success bool) *types.SuiteSummary { - numberOfSpecsThatWillBeRun := runner.countSpecsSatisfying(func(ex *spec.Spec) bool { - return !ex.Skipped() && !ex.Pending() - }) - - numberOfPendingSpecs := runner.countSpecsSatisfying(func(ex *spec.Spec) bool { - return ex.Pending() - }) - - numberOfSkippedSpecs := runner.countSpecsSatisfying(func(ex *spec.Spec) bool { - return ex.Skipped() - }) - - numberOfPassedSpecs := runner.countSpecsSatisfying(func(ex *spec.Spec) bool { - return ex.Passed() - }) - - numberOfFailedSpecs := runner.countSpecsSatisfying(func(ex *spec.Spec) bool { - return ex.Failed() - }) - - if runner.beforeSuiteNode != nil && !runner.beforeSuiteNode.Passed() && !runner.config.DryRun { - numberOfFailedSpecs = numberOfSpecsThatWillBeRun - } - - return &types.SuiteSummary{ - SuiteDescription: runner.description, - SuiteSucceeded: success, - SuiteID: runner.suiteID, - - NumberOfSpecsBeforeParallelization: runner.specs.NumberOfOriginalSpecs(), - NumberOfTotalSpecs: len(runner.specs.Specs()), - NumberOfSpecsThatWillBeRun: numberOfSpecsThatWillBeRun, - NumberOfPendingSpecs: numberOfPendingSpecs, - NumberOfSkippedSpecs: numberOfSkippedSpecs, - NumberOfPassedSpecs: numberOfPassedSpecs, - NumberOfFailedSpecs: numberOfFailedSpecs, - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go deleted file mode 100644 index c8388fb..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package specrunner_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestSpecRunner(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Spec Runner Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go deleted file mode 100644 index 99686d3..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go +++ /dev/null @@ -1,623 +0,0 @@ -package specrunner_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/specrunner" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - Writer "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" -) - -var noneFlag = types.FlagTypeNone -var focusedFlag = types.FlagTypeFocused -var pendingFlag = types.FlagTypePending - -var _ = Describe("Spec Runner", func() { - var ( - reporter1 *reporters.FakeReporter - reporter2 *reporters.FakeReporter - failer *Failer.Failer - writer *Writer.FakeGinkgoWriter - - thingsThatRan []string - - runner *SpecRunner - ) - - newBefSuite := func(text string, fail bool) leafnodes.SuiteNode { - return leafnodes.NewBeforeSuiteNode(func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - if fail { - failer.Fail(text, codelocation.New(0)) - } - }, codelocation.New(0), 0, failer) - } - - newAftSuite := func(text string, fail bool) leafnodes.SuiteNode { - return leafnodes.NewAfterSuiteNode(func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - if fail { - failer.Fail(text, codelocation.New(0)) - } - }, codelocation.New(0), 0, failer) - } - - newSpec := func(text string, flag types.FlagType, fail bool) *spec.Spec { - subject := leafnodes.NewItNode(text, func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - if fail { - failer.Fail(text, codelocation.New(0)) - } - }, flag, codelocation.New(0), 0, failer, 0) - - return spec.New(subject, []*containernode.ContainerNode{}, false) - } - - newSpecWithBody := func(text string, body interface{}) *spec.Spec { - subject := leafnodes.NewItNode(text, body, noneFlag, codelocation.New(0), 0, failer, 0) - - return spec.New(subject, []*containernode.ContainerNode{}, false) - } - - newRunner := func(config config.GinkgoConfigType, beforeSuiteNode leafnodes.SuiteNode, afterSuiteNode leafnodes.SuiteNode, specs ...*spec.Spec) *SpecRunner { - return New("description", beforeSuiteNode, spec.NewSpecs(specs), afterSuiteNode, []reporters.Reporter{reporter1, reporter2}, writer, config) - } - - BeforeEach(func() { - reporter1 = reporters.NewFakeReporter() - reporter2 = reporters.NewFakeReporter() - writer = Writer.NewFake() - failer = Failer.New() - - thingsThatRan = []string{} - }) - - Describe("Running and Reporting", func() { - var specA, pendingSpec, anotherPendingSpec, failedSpec, specB, skippedSpec *spec.Spec - var willRunCalls, didCompleteCalls []string - var conf config.GinkgoConfigType - - JustBeforeEach(func() { - willRunCalls = []string{} - didCompleteCalls = []string{} - specA = newSpec("spec A", noneFlag, false) - pendingSpec = newSpec("pending spec", pendingFlag, false) - anotherPendingSpec = newSpec("another pending spec", pendingFlag, false) - failedSpec = newSpec("failed spec", noneFlag, true) - specB = newSpec("spec B", noneFlag, false) - skippedSpec = newSpec("skipped spec", noneFlag, false) - skippedSpec.Skip() - - reporter1.SpecWillRunStub = func(specSummary *types.SpecSummary) { - willRunCalls = append(willRunCalls, "Reporter1") - } - reporter2.SpecWillRunStub = func(specSummary *types.SpecSummary) { - willRunCalls = append(willRunCalls, "Reporter2") - } - - reporter1.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - didCompleteCalls = append(didCompleteCalls, "Reporter1") - } - reporter2.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - didCompleteCalls = append(didCompleteCalls, "Reporter2") - } - - runner = newRunner(conf, newBefSuite("BefSuite", false), newAftSuite("AftSuite", false), specA, pendingSpec, anotherPendingSpec, failedSpec, specB, skippedSpec) - runner.Run() - }) - - BeforeEach(func() { - conf = config.GinkgoConfigType{RandomSeed: 17} - }) - - It("should skip skipped/pending tests", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "spec A", "failed spec", "spec B", "AftSuite"})) - }) - - It("should report to any attached reporters", func() { - Ω(reporter1.Config).Should(Equal(reporter2.Config)) - Ω(reporter1.BeforeSuiteSummary).Should(Equal(reporter2.BeforeSuiteSummary)) - Ω(reporter1.BeginSummary).Should(Equal(reporter2.BeginSummary)) - Ω(reporter1.SpecWillRunSummaries).Should(Equal(reporter2.SpecWillRunSummaries)) - Ω(reporter1.SpecSummaries).Should(Equal(reporter2.SpecSummaries)) - Ω(reporter1.AfterSuiteSummary).Should(Equal(reporter2.AfterSuiteSummary)) - Ω(reporter1.EndSummary).Should(Equal(reporter2.EndSummary)) - }) - - It("should report that a spec did end in reverse order", func() { - Ω(willRunCalls[0:4]).Should(Equal([]string{"Reporter1", "Reporter2", "Reporter1", "Reporter2"})) - Ω(didCompleteCalls[0:4]).Should(Equal([]string{"Reporter2", "Reporter1", "Reporter2", "Reporter1"})) - }) - - It("should report the passed in config", func() { - Ω(reporter1.Config.RandomSeed).Should(BeNumerically("==", 17)) - }) - - It("should report the beginning of the suite", func() { - Ω(reporter1.BeginSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.BeginSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.BeginSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.BeginSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.BeginSummary.NumberOfSpecsThatWillBeRun).Should(Equal(3)) - Ω(reporter1.BeginSummary.NumberOfPendingSpecs).Should(Equal(2)) - Ω(reporter1.BeginSummary.NumberOfSkippedSpecs).Should(Equal(1)) - }) - - It("should report the end of the suite", func() { - Ω(reporter1.EndSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(3)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPassedSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(1)) - }) - - Context("when told to perform a dry run", func() { - BeforeEach(func() { - conf.DryRun = true - }) - - It("should report to the reporters", func() { - Ω(reporter1.Config).Should(Equal(reporter2.Config)) - Ω(reporter1.BeforeSuiteSummary).Should(Equal(reporter2.BeforeSuiteSummary)) - Ω(reporter1.BeginSummary).Should(Equal(reporter2.BeginSummary)) - Ω(reporter1.SpecWillRunSummaries).Should(Equal(reporter2.SpecWillRunSummaries)) - Ω(reporter1.SpecSummaries).Should(Equal(reporter2.SpecSummaries)) - Ω(reporter1.AfterSuiteSummary).Should(Equal(reporter2.AfterSuiteSummary)) - Ω(reporter1.EndSummary).Should(Equal(reporter2.EndSummary)) - }) - - It("should not actually run anything", func() { - Ω(thingsThatRan).Should(BeEmpty()) - }) - - It("report before and after suites as passed", func() { - Ω(reporter1.BeforeSuiteSummary.State).Should(Equal(types.SpecStatePassed)) - Ω(reporter1.AfterSuiteSummary.State).Should(Equal(types.SpecStatePassed)) - }) - - It("should report specs as passed", func() { - summaries := reporter1.SpecSummaries - Ω(summaries).Should(HaveLen(6)) - Ω(summaries[0].ComponentTexts).Should(ContainElement("spec A")) - Ω(summaries[0].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[1].ComponentTexts).Should(ContainElement("pending spec")) - Ω(summaries[1].State).Should(Equal(types.SpecStatePending)) - Ω(summaries[2].ComponentTexts).Should(ContainElement("another pending spec")) - Ω(summaries[2].State).Should(Equal(types.SpecStatePending)) - Ω(summaries[3].ComponentTexts).Should(ContainElement("failed spec")) - Ω(summaries[3].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[4].ComponentTexts).Should(ContainElement("spec B")) - Ω(summaries[4].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[5].ComponentTexts).Should(ContainElement("skipped spec")) - Ω(summaries[5].State).Should(Equal(types.SpecStateSkipped)) - }) - - It("should report the end of the suite", func() { - Ω(reporter1.EndSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(3)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPassedSpecs).Should(Equal(0)) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - }) - }) - - Describe("reporting on specs", func() { - var proceed chan bool - var ready chan bool - var finished chan bool - BeforeEach(func() { - ready = make(chan bool) - proceed = make(chan bool) - finished = make(chan bool) - skippedSpec := newSpec("SKIP", noneFlag, false) - skippedSpec.Skip() - - runner = newRunner( - config.GinkgoConfigType{}, - newBefSuite("BefSuite", false), - newAftSuite("AftSuite", false), - skippedSpec, - newSpec("PENDING", pendingFlag, false), - newSpecWithBody("RUN", func() { - close(ready) - <-proceed - }), - ) - go func() { - runner.Run() - close(finished) - }() - }) - - It("should report about pending/skipped specs", func() { - <-ready - Ω(reporter1.SpecWillRunSummaries).Should(HaveLen(3)) - - Ω(reporter1.SpecWillRunSummaries[0].ComponentTexts[0]).Should(Equal("SKIP")) - Ω(reporter1.SpecWillRunSummaries[1].ComponentTexts[0]).Should(Equal("PENDING")) - Ω(reporter1.SpecWillRunSummaries[2].ComponentTexts[0]).Should(Equal("RUN")) - - Ω(reporter1.SpecSummaries[0].ComponentTexts[0]).Should(Equal("SKIP")) - Ω(reporter1.SpecSummaries[1].ComponentTexts[0]).Should(Equal("PENDING")) - Ω(reporter1.SpecSummaries).Should(HaveLen(2)) - - close(proceed) - <-finished - - Ω(reporter1.SpecSummaries).Should(HaveLen(3)) - Ω(reporter1.SpecSummaries[2].ComponentTexts[0]).Should(Equal("RUN")) - }) - }) - - Describe("Running BeforeSuite & AfterSuite", func() { - var success bool - var befSuite leafnodes.SuiteNode - var aftSuite leafnodes.SuiteNode - Context("with a nil BeforeSuite & AfterSuite", func() { - BeforeEach(func() { - runner = newRunner( - config.GinkgoConfigType{}, - nil, - nil, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - ) - success = runner.Run() - }) - - It("should not report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(BeNil()) - }) - - It("should not report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(BeNil()) - }) - - It("should run the specs", func() { - Ω(thingsThatRan).Should(Equal([]string{"A", "B"})) - }) - }) - - Context("when the BeforeSuite & AfterSuite pass", func() { - BeforeEach(func() { - befSuite = newBefSuite("BefSuite", false) - aftSuite = newBefSuite("AftSuite", false) - runner = newRunner( - config.GinkgoConfigType{}, - befSuite, - aftSuite, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - ) - success = runner.Run() - }) - - It("should run the BeforeSuite, the AfterSuite and the specs", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "A", "B", "AftSuite"})) - }) - - It("should report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(Equal(befSuite.Summary())) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report success", func() { - Ω(success).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - - It("should not dump the writer", func() { - Ω(writer.EventStream).ShouldNot(ContainElement("DUMP")) - }) - }) - - Context("when the BeforeSuite fails", func() { - BeforeEach(func() { - befSuite = newBefSuite("BefSuite", true) - aftSuite = newBefSuite("AftSuite", false) - - skipped := newSpec("Skipped", noneFlag, false) - skipped.Skip() - - runner = newRunner( - config.GinkgoConfigType{}, - befSuite, - aftSuite, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - newSpec("Pending", pendingFlag, false), - skipped, - ) - success = runner.Run() - }) - - It("should not run the specs, but it should run the AfterSuite", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "AftSuite"})) - }) - - It("should report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(Equal(befSuite.Summary())) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report failure", func() { - Ω(success).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(2)) - }) - - It("should dump the writer", func() { - Ω(writer.EventStream).Should(ContainElement("DUMP")) - }) - }) - - Context("when some other test fails", func() { - BeforeEach(func() { - aftSuite = newBefSuite("AftSuite", false) - - runner = newRunner( - config.GinkgoConfigType{}, - nil, - aftSuite, - newSpec("A", noneFlag, true), - ) - success = runner.Run() - }) - - It("should still run the AfterSuite", func() { - Ω(thingsThatRan).Should(Equal([]string{"A", "AftSuite"})) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report failure", func() { - Ω(success).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(1)) - }) - }) - - Context("when the AfterSuite fails", func() { - BeforeEach(func() { - befSuite = newBefSuite("BefSuite", false) - aftSuite = newBefSuite("AftSuite", true) - runner = newRunner( - config.GinkgoConfigType{}, - befSuite, - aftSuite, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - ) - success = runner.Run() - }) - - It("should run everything", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "A", "B", "AftSuite"})) - }) - - It("should report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(Equal(befSuite.Summary())) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report failure", func() { - Ω(success).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - - It("should dump the writer", func() { - Ω(writer.EventStream).Should(ContainElement("DUMP")) - }) - }) - }) - - Describe("When instructed to fail fast", func() { - BeforeEach(func() { - conf := config.GinkgoConfigType{ - FailFast: true, - } - runner = newRunner(conf, nil, newAftSuite("after-suite", false), newSpec("passing", noneFlag, false), newSpec("failing", noneFlag, true), newSpec("dont-see", noneFlag, true), newSpec("dont-see", noneFlag, true)) - }) - - It("should return false, report failure, and not run anything past the failing test", func() { - Ω(runner.Run()).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(thingsThatRan).Should(Equal([]string{"passing", "failing", "after-suite"})) - }) - - It("should announce the subsequent specs as skipped", func() { - runner.Run() - Ω(reporter1.SpecSummaries).Should(HaveLen(4)) - Ω(reporter1.SpecSummaries[2].State).Should(Equal(types.SpecStateSkipped)) - Ω(reporter1.SpecSummaries[3].State).Should(Equal(types.SpecStateSkipped)) - }) - - It("should mark all subsequent specs as skipped", func() { - runner.Run() - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(2)) - }) - }) - - Describe("Marking failure and success", func() { - Context("when all tests pass", func() { - BeforeEach(func() { - runner = newRunner(config.GinkgoConfigType{}, nil, nil, newSpec("passing", noneFlag, false), newSpec("pending", pendingFlag, false)) - }) - - It("should return true and report success", func() { - Ω(runner.Run()).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - }) - }) - - Context("when a test fails", func() { - BeforeEach(func() { - runner = newRunner(config.GinkgoConfigType{}, nil, nil, newSpec("failing", noneFlag, true), newSpec("pending", pendingFlag, false)) - }) - - It("should return false and report failure", func() { - Ω(runner.Run()).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - }) - }) - - Context("when there is a pending test, but pendings count as failures", func() { - BeforeEach(func() { - runner = newRunner(config.GinkgoConfigType{FailOnPending: true}, nil, nil, newSpec("passing", noneFlag, false), newSpec("pending", pendingFlag, false)) - }) - - It("should return false and report failure", func() { - Ω(runner.Run()).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - }) - }) - }) - - Describe("Managing the writer", func() { - BeforeEach(func() { - runner = newRunner( - config.GinkgoConfigType{}, - nil, - nil, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, true), - newSpec("C", noneFlag, false), - ) - reporter1.SpecWillRunStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R1.WillRun") - } - reporter2.SpecWillRunStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R2.WillRun") - } - reporter1.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R1.DidComplete") - } - reporter2.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R2.DidComplete") - } - runner.Run() - }) - - It("should truncate between tests, but only dump if a test fails", func() { - Ω(writer.EventStream).Should(Equal([]string{ - "TRUNCATE", - "R1.WillRun", - "R2.WillRun", - "A", - "R2.DidComplete", - "R1.DidComplete", - "TRUNCATE", - "R1.WillRun", - "R2.WillRun", - "B", - "R2.DidComplete", - "DUMP", - "R1.DidComplete", - "TRUNCATE", - "R1.WillRun", - "R2.WillRun", - "C", - "R2.DidComplete", - "R1.DidComplete", - })) - }) - }) - - Describe("CurrentSpecSummary", func() { - It("should return the spec summary for the currently running spec", func() { - var summary *types.SpecSummary - runner = newRunner( - config.GinkgoConfigType{}, - nil, - nil, - newSpec("A", noneFlag, false), - newSpecWithBody("B", func() { - var ok bool - summary, ok = runner.CurrentSpecSummary() - Ω(ok).Should(BeTrue()) - }), - newSpec("C", noneFlag, false), - ) - runner.Run() - - Ω(summary.ComponentTexts).Should(Equal([]string{"B"})) - - summary, ok := runner.CurrentSpecSummary() - Ω(summary).Should(BeNil()) - Ω(ok).Should(BeFalse()) - }) - }) - - Context("When running tests in parallel", func() { - It("reports the correct number of specs before parallelization", func() { - specs := spec.NewSpecs([]*spec.Spec{ - newSpec("A", noneFlag, false), - newSpec("B", pendingFlag, false), - newSpec("C", noneFlag, false), - }) - specs.TrimForParallelization(2, 1) - runner = New("description", nil, specs, nil, []reporters.Reporter{reporter1, reporter2}, writer, config.GinkgoConfigType{}) - runner.Run() - - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(3)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(1)) - }) - }) - - Describe("generating a suite id", func() { - It("should generate an id randomly", func() { - runnerA := newRunner(config.GinkgoConfigType{}, nil, nil) - runnerA.Run() - IDA := reporter1.BeginSummary.SuiteID - - runnerB := newRunner(config.GinkgoConfigType{}, nil, nil) - runnerB.Run() - IDB := reporter1.BeginSummary.SuiteID - - IDRegexp := "[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}" - Ω(IDA).Should(MatchRegexp(IDRegexp)) - Ω(IDB).Should(MatchRegexp(IDRegexp)) - - Ω(IDA).ShouldNot(Equal(IDB)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite.go deleted file mode 100644 index a054602..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite.go +++ /dev/null @@ -1,171 +0,0 @@ -package suite - -import ( - "math/rand" - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - "github.com/onsi/ginkgo/internal/specrunner" - "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" -) - -type ginkgoTestingT interface { - Fail() -} - -type Suite struct { - topLevelContainer *containernode.ContainerNode - currentContainer *containernode.ContainerNode - containerIndex int - beforeSuiteNode leafnodes.SuiteNode - afterSuiteNode leafnodes.SuiteNode - runner *specrunner.SpecRunner - failer *failer.Failer - running bool -} - -func New(failer *failer.Failer) *Suite { - topLevelContainer := containernode.New("[Top Level]", types.FlagTypeNone, types.CodeLocation{}) - - return &Suite{ - topLevelContainer: topLevelContainer, - currentContainer: topLevelContainer, - failer: failer, - containerIndex: 1, - } -} - -func (suite *Suite) Run(t ginkgoTestingT, description string, reporters []reporters.Reporter, writer writer.WriterInterface, config config.GinkgoConfigType) (bool, bool) { - if config.ParallelTotal < 1 { - panic("ginkgo.parallel.total must be >= 1") - } - - if config.ParallelNode > config.ParallelTotal || config.ParallelNode < 1 { - panic("ginkgo.parallel.node is one-indexed and must be <= ginkgo.parallel.total") - } - - r := rand.New(rand.NewSource(config.RandomSeed)) - suite.topLevelContainer.Shuffle(r) - specs := suite.generateSpecs(description, config) - suite.runner = specrunner.New(description, suite.beforeSuiteNode, specs, suite.afterSuiteNode, reporters, writer, config) - - suite.running = true - success := suite.runner.Run() - if !success { - t.Fail() - } - return success, specs.HasProgrammaticFocus() -} - -func (suite *Suite) generateSpecs(description string, config config.GinkgoConfigType) *spec.Specs { - specsSlice := []*spec.Spec{} - suite.topLevelContainer.BackPropagateProgrammaticFocus() - for _, collatedNodes := range suite.topLevelContainer.Collate() { - specsSlice = append(specsSlice, spec.New(collatedNodes.Subject, collatedNodes.Containers, config.EmitSpecProgress)) - } - - specs := spec.NewSpecs(specsSlice) - - if config.RandomizeAllSpecs { - specs.Shuffle(rand.New(rand.NewSource(config.RandomSeed))) - } - - specs.ApplyFocus(description, config.FocusString, config.SkipString) - - if config.SkipMeasurements { - specs.SkipMeasurements() - } - - if config.ParallelTotal > 1 { - specs.TrimForParallelization(config.ParallelTotal, config.ParallelNode) - } - - return specs -} - -func (suite *Suite) CurrentRunningSpecSummary() (*types.SpecSummary, bool) { - return suite.runner.CurrentSpecSummary() -} - -func (suite *Suite) SetBeforeSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.beforeSuiteNode != nil { - panic("You may only call BeforeSuite once!") - } - suite.beforeSuiteNode = leafnodes.NewBeforeSuiteNode(body, codeLocation, timeout, suite.failer) -} - -func (suite *Suite) SetAfterSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.afterSuiteNode != nil { - panic("You may only call AfterSuite once!") - } - suite.afterSuiteNode = leafnodes.NewAfterSuiteNode(body, codeLocation, timeout, suite.failer) -} - -func (suite *Suite) SetSynchronizedBeforeSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.beforeSuiteNode != nil { - panic("You may only call BeforeSuite once!") - } - suite.beforeSuiteNode = leafnodes.NewSynchronizedBeforeSuiteNode(bodyA, bodyB, codeLocation, timeout, suite.failer) -} - -func (suite *Suite) SetSynchronizedAfterSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.afterSuiteNode != nil { - panic("You may only call AfterSuite once!") - } - suite.afterSuiteNode = leafnodes.NewSynchronizedAfterSuiteNode(bodyA, bodyB, codeLocation, timeout, suite.failer) -} - -func (suite *Suite) PushContainerNode(text string, body func(), flag types.FlagType, codeLocation types.CodeLocation) { - container := containernode.New(text, flag, codeLocation) - suite.currentContainer.PushContainerNode(container) - - previousContainer := suite.currentContainer - suite.currentContainer = container - suite.containerIndex++ - - body() - - suite.containerIndex-- - suite.currentContainer = previousContainer -} - -func (suite *Suite) PushItNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call It from within a Describe or Context", codeLocation) - } - suite.currentContainer.PushSubjectNode(leafnodes.NewItNode(text, body, flag, codeLocation, timeout, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushMeasureNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, samples int) { - if suite.running { - suite.failer.Fail("You may only call Measure from within a Describe or Context", codeLocation) - } - suite.currentContainer.PushSubjectNode(leafnodes.NewMeasureNode(text, body, flag, codeLocation, samples, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call BeforeEach from within a Describe or Context", codeLocation) - } - suite.currentContainer.PushSetupNode(leafnodes.NewBeforeEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushJustBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call JustBeforeEach from within a Describe or Context", codeLocation) - } - suite.currentContainer.PushSetupNode(leafnodes.NewJustBeforeEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushAfterEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call AfterEach from within a Describe or Context", codeLocation) - } - suite.currentContainer.PushSetupNode(leafnodes.NewAfterEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go deleted file mode 100644 index 06fe1d1..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package suite_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func Test(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Suite") -} - -var numBeforeSuiteRuns = 0 -var numAfterSuiteRuns = 0 - -var _ = BeforeSuite(func() { - numBeforeSuiteRuns++ -}) - -var _ = AfterSuite(func() { - numAfterSuiteRuns++ - Ω(numBeforeSuiteRuns).Should(Equal(1)) - Ω(numAfterSuiteRuns).Should(Equal(1)) -}) - -//Fakes -type fakeTestingT struct { - didFail bool -} - -func (fakeT *fakeTestingT) Fail() { - fakeT.didFail = true -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_test.go deleted file mode 100644 index dd471b4..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_test.go +++ /dev/null @@ -1,399 +0,0 @@ -package suite_test - -import ( - "bytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/suite" - . "github.com/onsi/gomega" - - "math/rand" - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - Writer "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Suite", func() { - var ( - specSuite *Suite - fakeT *fakeTestingT - fakeR *reporters.FakeReporter - writer *Writer.FakeGinkgoWriter - failer *Failer.Failer - ) - - BeforeEach(func() { - writer = Writer.NewFake() - fakeT = &fakeTestingT{} - fakeR = reporters.NewFakeReporter() - failer = Failer.New() - specSuite = New(failer) - }) - - Describe("running a suite", func() { - var ( - runOrder []string - randomizeAllSpecs bool - randomSeed int64 - focusString string - parallelNode int - parallelTotal int - runResult bool - hasProgrammaticFocus bool - ) - - var f = func(runText string) func() { - return func() { - runOrder = append(runOrder, runText) - } - } - - BeforeEach(func() { - randomizeAllSpecs = false - randomSeed = 11 - parallelNode = 1 - parallelTotal = 1 - focusString = "" - - runOrder = make([]string, 0) - specSuite.SetBeforeSuiteNode(f("BeforeSuite"), codelocation.New(0), 0) - specSuite.PushBeforeEachNode(f("top BE"), codelocation.New(0), 0) - specSuite.PushJustBeforeEachNode(f("top JBE"), codelocation.New(0), 0) - specSuite.PushAfterEachNode(f("top AE"), codelocation.New(0), 0) - - specSuite.PushContainerNode("container", func() { - specSuite.PushBeforeEachNode(f("BE"), codelocation.New(0), 0) - specSuite.PushJustBeforeEachNode(f("JBE"), codelocation.New(0), 0) - specSuite.PushAfterEachNode(f("AE"), codelocation.New(0), 0) - specSuite.PushItNode("it", f("IT"), types.FlagTypeNone, codelocation.New(0), 0) - - specSuite.PushContainerNode("inner container", func() { - specSuite.PushItNode("inner it", f("inner IT"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0)) - }, types.FlagTypeNone, codelocation.New(0)) - - specSuite.PushContainerNode("container 2", func() { - specSuite.PushBeforeEachNode(f("BE 2"), codelocation.New(0), 0) - specSuite.PushItNode("it 2", f("IT 2"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0)) - - specSuite.PushItNode("top level it", f("top IT"), types.FlagTypeNone, codelocation.New(0), 0) - - specSuite.SetAfterSuiteNode(f("AfterSuite"), codelocation.New(0), 0) - }) - - JustBeforeEach(func() { - runResult, hasProgrammaticFocus = specSuite.Run(fakeT, "suite description", []reporters.Reporter{fakeR}, writer, config.GinkgoConfigType{ - RandomSeed: randomSeed, - RandomizeAllSpecs: randomizeAllSpecs, - FocusString: focusString, - ParallelNode: parallelNode, - ParallelTotal: parallelTotal, - }) - }) - - It("provides the config and suite description to the reporter", func() { - Ω(fakeR.Config.RandomSeed).Should(Equal(int64(randomSeed))) - Ω(fakeR.Config.RandomizeAllSpecs).Should(Equal(randomizeAllSpecs)) - Ω(fakeR.BeginSummary.SuiteDescription).Should(Equal("suite description")) - }) - - It("reports that the BeforeSuite node ran", func() { - Ω(fakeR.BeforeSuiteSummary).ShouldNot(BeNil()) - }) - - It("reports that the AfterSuite node ran", func() { - Ω(fakeR.AfterSuiteSummary).ShouldNot(BeNil()) - }) - - It("provides information about the current test", func() { - description := CurrentGinkgoTestDescription() - Ω(description.ComponentTexts).Should(Equal([]string{"Suite", "running a suite", "provides information about the current test"})) - Ω(description.FullTestText).Should(Equal("Suite running a suite provides information about the current test")) - Ω(description.TestText).Should(Equal("provides information about the current test")) - Ω(description.IsMeasurement).Should(BeFalse()) - Ω(description.FileName).Should(ContainSubstring("suite_test.go")) - Ω(description.LineNumber).Should(BeNumerically(">", 50)) - Ω(description.LineNumber).Should(BeNumerically("<", 150)) - Ω(description.Failed).Should(BeFalse()) - }) - - Measure("should run measurements", func(b Benchmarker) { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - - runtime := b.Time("sleeping", func() { - sleepTime := time.Duration(r.Float64() * 0.01 * float64(time.Second)) - time.Sleep(sleepTime) - }) - Ω(runtime.Seconds()).Should(BeNumerically("<=", 0.015)) - Ω(runtime.Seconds()).Should(BeNumerically(">=", 0)) - - randomValue := r.Float64() * 10.0 - b.RecordValue("random value", randomValue) - Ω(randomValue).Should(BeNumerically("<=", 10.0)) - Ω(randomValue).Should(BeNumerically(">=", 0.0)) - }, 10) - - It("creates a node hierarchy, converts it to a spec collection, and runs it", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "BE", "top JBE", "JBE", "IT", "AE", "top AE", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "top BE", "top JBE", "top IT", "top AE", - "AfterSuite", - })) - }) - - Context("when told to randomize all specs", func() { - BeforeEach(func() { - randomizeAllSpecs = true - }) - - It("does", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "top JBE", "top IT", "top AE", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "top BE", "BE", "top JBE", "JBE", "IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "AfterSuite", - })) - }) - }) - - Describe("with ginkgo.parallel.total > 1", func() { - BeforeEach(func() { - parallelTotal = 2 - randomizeAllSpecs = true - }) - - Context("for one worker", func() { - BeforeEach(func() { - parallelNode = 1 - }) - - It("should run a subset of tests", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "top JBE", "top IT", "top AE", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "AfterSuite", - })) - }) - }) - - Context("for another worker", func() { - BeforeEach(func() { - parallelNode = 2 - }) - - It("should run a (different) subset of tests", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "BE", "top JBE", "JBE", "IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "AfterSuite", - })) - }) - }) - }) - - Context("when provided with a filter", func() { - BeforeEach(func() { - focusString = `inner|\d` - }) - - It("converts the filter to a regular expression and uses it to filter the running specs", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "AfterSuite", - })) - }) - - It("should not report a programmatic focus", func() { - Ω(hasProgrammaticFocus).Should(BeFalse()) - }) - }) - - Context("with a programatically focused spec", func() { - BeforeEach(func() { - specSuite.PushItNode("focused it", f("focused it"), types.FlagTypeFocused, codelocation.New(0), 0) - - specSuite.PushContainerNode("focused container", func() { - specSuite.PushItNode("inner focused it", f("inner focused it"), types.FlagTypeFocused, codelocation.New(0), 0) - specSuite.PushItNode("inner unfocused it", f("inner unfocused it"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeFocused, codelocation.New(0)) - - }) - - It("should only run the focused test, applying backpropagation to favor most deeply focused leaf nodes", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "top JBE", "focused it", "top AE", - "top BE", "top JBE", "inner focused it", "top AE", - "AfterSuite", - })) - }) - - It("should report a programmatic focus", func() { - Ω(hasProgrammaticFocus).Should(BeTrue()) - }) - }) - - Context("when the specs pass", func() { - It("doesn't report a failure", func() { - Ω(fakeT.didFail).Should(BeFalse()) - }) - - It("should return true", func() { - Ω(runResult).Should(BeTrue()) - }) - }) - - Context("when a spec fails", func() { - var location types.CodeLocation - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - location = codelocation.New(0) - failer.Fail("oops!", location) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should return false", func() { - Ω(runResult).Should(BeFalse()) - }) - - It("reports a failure", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - - It("generates the correct failure data", func() { - Ω(fakeR.SpecSummaries[0].Failure.Message).Should(Equal("oops!")) - Ω(fakeR.SpecSummaries[0].Failure.Location).Should(Equal(location)) - }) - }) - - Context("when runnable nodes are nested within other runnable nodes", func() { - Context("when an It is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushItNode("nested it", f("oops"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a Measure is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushMeasureNode("nested measure", func(Benchmarker) {}, types.FlagTypeNone, codelocation.New(0), 10) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a BeforeEach is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushBeforeEachNode(f("nested bef"), codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a JustBeforeEach is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushJustBeforeEachNode(f("nested jbef"), codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a AfterEach is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushAfterEachNode(f("nested aft"), codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - }) - }) - - Describe("BeforeSuite", func() { - Context("when setting BeforeSuite more than once", func() { - It("should panic", func() { - specSuite.SetBeforeSuiteNode(func() {}, codelocation.New(0), 0) - - Ω(func() { - specSuite.SetBeforeSuiteNode(func() {}, codelocation.New(0), 0) - }).Should(Panic()) - - }) - }) - }) - - Describe("AfterSuite", func() { - Context("when setting AfterSuite more than once", func() { - It("should panic", func() { - specSuite.SetAfterSuiteNode(func() {}, codelocation.New(0), 0) - - Ω(func() { - specSuite.SetAfterSuiteNode(func() {}, codelocation.New(0), 0) - }).Should(Panic()) - }) - }) - }) - - Describe("By", func() { - It("writes to the GinkgoWriter", func() { - originalGinkgoWriter := GinkgoWriter - buffer := &bytes.Buffer{} - - GinkgoWriter = buffer - By("Saying Hello GinkgoWriter") - GinkgoWriter = originalGinkgoWriter - - Ω(buffer.String()).Should(ContainSubstring("STEP")) - Ω(buffer.String()).Should(ContainSubstring(": Saying Hello GinkgoWriter\n")) - }) - - It("calls the passed-in callback if present", func() { - a := 0 - By("calling the callback", func() { - a = 1 - }) - Ω(a).Should(Equal(1)) - }) - - It("panics if there is more than one callback", func() { - Ω(func() { - By("registering more than one callback", func() {}, func() {}) - }).Should(Panic()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/testingtproxy/testing_t_proxy.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/testingtproxy/testing_t_proxy.go deleted file mode 100644 index a2b9af8..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/testingtproxy/testing_t_proxy.go +++ /dev/null @@ -1,76 +0,0 @@ -package testingtproxy - -import ( - "fmt" - "io" -) - -type failFunc func(message string, callerSkip ...int) - -func New(writer io.Writer, fail failFunc, offset int) *ginkgoTestingTProxy { - return &ginkgoTestingTProxy{ - fail: fail, - offset: offset, - writer: writer, - } -} - -type ginkgoTestingTProxy struct { - fail failFunc - offset int - writer io.Writer -} - -func (t *ginkgoTestingTProxy) Error(args ...interface{}) { - t.fail(fmt.Sprintln(args...), t.offset) -} - -func (t *ginkgoTestingTProxy) Errorf(format string, args ...interface{}) { - t.fail(fmt.Sprintf(format, args...), t.offset) -} - -func (t *ginkgoTestingTProxy) Fail() { - t.fail("failed", t.offset) -} - -func (t *ginkgoTestingTProxy) FailNow() { - t.fail("failed", t.offset) -} - -func (t *ginkgoTestingTProxy) Fatal(args ...interface{}) { - t.fail(fmt.Sprintln(args...), t.offset) -} - -func (t *ginkgoTestingTProxy) Fatalf(format string, args ...interface{}) { - t.fail(fmt.Sprintf(format, args...), t.offset) -} - -func (t *ginkgoTestingTProxy) Log(args ...interface{}) { - fmt.Fprintln(t.writer, args...) -} - -func (t *ginkgoTestingTProxy) Logf(format string, args ...interface{}) { - fmt.Fprintf(t.writer, format, args...) -} - -func (t *ginkgoTestingTProxy) Failed() bool { - return false -} - -func (t *ginkgoTestingTProxy) Parallel() { -} - -func (t *ginkgoTestingTProxy) Skip(args ...interface{}) { - fmt.Println(args...) -} - -func (t *ginkgoTestingTProxy) Skipf(format string, args ...interface{}) { - fmt.Printf(format, args...) -} - -func (t *ginkgoTestingTProxy) SkipNow() { -} - -func (t *ginkgoTestingTProxy) Skipped() bool { - return false -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/fake_writer.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/fake_writer.go deleted file mode 100644 index ac6540f..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/fake_writer.go +++ /dev/null @@ -1,31 +0,0 @@ -package writer - -type FakeGinkgoWriter struct { - EventStream []string -} - -func NewFake() *FakeGinkgoWriter { - return &FakeGinkgoWriter{ - EventStream: []string{}, - } -} - -func (writer *FakeGinkgoWriter) AddEvent(event string) { - writer.EventStream = append(writer.EventStream, event) -} - -func (writer *FakeGinkgoWriter) Truncate() { - writer.EventStream = append(writer.EventStream, "TRUNCATE") -} - -func (writer *FakeGinkgoWriter) DumpOut() { - writer.EventStream = append(writer.EventStream, "DUMP") -} - -func (writer *FakeGinkgoWriter) DumpOutWithHeader(header string) { - writer.EventStream = append(writer.EventStream, "DUMP_WITH_HEADER: "+header) -} - -func (writer *FakeGinkgoWriter) Write(data []byte) (n int, err error) { - return 0, nil -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer.go deleted file mode 100644 index 7678fc1..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer.go +++ /dev/null @@ -1,71 +0,0 @@ -package writer - -import ( - "bytes" - "io" - "sync" -) - -type WriterInterface interface { - io.Writer - - Truncate() - DumpOut() - DumpOutWithHeader(header string) -} - -type Writer struct { - buffer *bytes.Buffer - outWriter io.Writer - lock *sync.Mutex - stream bool -} - -func New(outWriter io.Writer) *Writer { - return &Writer{ - buffer: &bytes.Buffer{}, - lock: &sync.Mutex{}, - outWriter: outWriter, - stream: true, - } -} - -func (w *Writer) SetStream(stream bool) { - w.lock.Lock() - defer w.lock.Unlock() - w.stream = stream -} - -func (w *Writer) Write(b []byte) (n int, err error) { - w.lock.Lock() - defer w.lock.Unlock() - - if w.stream { - return w.outWriter.Write(b) - } else { - return w.buffer.Write(b) - } -} - -func (w *Writer) Truncate() { - w.lock.Lock() - defer w.lock.Unlock() - w.buffer.Reset() -} - -func (w *Writer) DumpOut() { - w.lock.Lock() - defer w.lock.Unlock() - if !w.stream { - w.buffer.WriteTo(w.outWriter) - } -} - -func (w *Writer) DumpOutWithHeader(header string) { - w.lock.Lock() - defer w.lock.Unlock() - if !w.stream && w.buffer.Len() > 0 { - w.outWriter.Write([]byte(header)) - w.buffer.WriteTo(w.outWriter) - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go deleted file mode 100644 index e206577..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package writer_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestWriter(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Writer Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_test.go deleted file mode 100644 index 3e1d17c..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package writer_test - -import ( - "github.com/onsi/gomega/gbytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/writer" - . "github.com/onsi/gomega" -) - -var _ = Describe("Writer", func() { - var writer *Writer - var out *gbytes.Buffer - - BeforeEach(func() { - out = gbytes.NewBuffer() - writer = New(out) - }) - - It("should stream directly to the outbuffer by default", func() { - writer.Write([]byte("foo")) - Ω(out).Should(gbytes.Say("foo")) - }) - - It("should not emit the header when asked to DumpOutWitHeader", func() { - writer.Write([]byte("foo")) - writer.DumpOutWithHeader("my header") - Ω(out).ShouldNot(gbytes.Say("my header")) - Ω(out).Should(gbytes.Say("foo")) - }) - - Context("when told not to stream", func() { - BeforeEach(func() { - writer.SetStream(false) - }) - - It("should only write to the buffer when told to DumpOut", func() { - writer.Write([]byte("foo")) - Ω(out).ShouldNot(gbytes.Say("foo")) - writer.DumpOut() - Ω(out).Should(gbytes.Say("foo")) - }) - - It("should truncate the internal buffer when told to truncate", func() { - writer.Write([]byte("foo")) - writer.Truncate() - writer.DumpOut() - Ω(out).ShouldNot(gbytes.Say("foo")) - - writer.Write([]byte("bar")) - writer.DumpOut() - Ω(out).Should(gbytes.Say("bar")) - }) - - Describe("emitting a header", func() { - Context("when the buffer has content", func() { - It("should emit the header followed by the content", func() { - writer.Write([]byte("foo")) - writer.DumpOutWithHeader("my header") - - Ω(out).Should(gbytes.Say("my header")) - Ω(out).Should(gbytes.Say("foo")) - }) - }) - - Context("when the buffer has no content", func() { - It("should not emit the header", func() { - writer.DumpOutWithHeader("my header") - - Ω(out).ShouldNot(gbytes.Say("my header")) - }) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/default_reporter.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/default_reporter.go deleted file mode 100644 index 45a44de..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/default_reporter.go +++ /dev/null @@ -1,83 +0,0 @@ -/* -Ginkgo's Default Reporter - -A number of command line flags are available to tweak Ginkgo's default output. - -These are documented [here](http://onsi.github.io/ginkgo/#running_tests) -*/ -package reporters - -import ( - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" -) - -type DefaultReporter struct { - config config.DefaultReporterConfigType - stenographer stenographer.Stenographer - specSummaries []*types.SpecSummary -} - -func NewDefaultReporter(config config.DefaultReporterConfigType, stenographer stenographer.Stenographer) *DefaultReporter { - return &DefaultReporter{ - config: config, - stenographer: stenographer, - } -} - -func (reporter *DefaultReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - reporter.stenographer.AnnounceSuite(summary.SuiteDescription, config.RandomSeed, config.RandomizeAllSpecs, reporter.config.Succinct) - if config.ParallelTotal > 1 { - reporter.stenographer.AnnounceParallelRun(config.ParallelNode, config.ParallelTotal, summary.NumberOfTotalSpecs, summary.NumberOfSpecsBeforeParallelization, reporter.config.Succinct) - } - reporter.stenographer.AnnounceNumberOfSpecs(summary.NumberOfSpecsThatWillBeRun, summary.NumberOfTotalSpecs, reporter.config.Succinct) -} - -func (reporter *DefaultReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - if setupSummary.State != types.SpecStatePassed { - reporter.stenographer.AnnounceBeforeSuiteFailure(setupSummary, reporter.config.Succinct, reporter.config.FullTrace) - } -} - -func (reporter *DefaultReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - if setupSummary.State != types.SpecStatePassed { - reporter.stenographer.AnnounceAfterSuiteFailure(setupSummary, reporter.config.Succinct, reporter.config.FullTrace) - } -} - -func (reporter *DefaultReporter) SpecWillRun(specSummary *types.SpecSummary) { - if reporter.config.Verbose && !reporter.config.Succinct && specSummary.State != types.SpecStatePending && specSummary.State != types.SpecStateSkipped { - reporter.stenographer.AnnounceSpecWillRun(specSummary) - } -} - -func (reporter *DefaultReporter) SpecDidComplete(specSummary *types.SpecSummary) { - switch specSummary.State { - case types.SpecStatePassed: - if specSummary.IsMeasurement { - reporter.stenographer.AnnounceSuccesfulMeasurement(specSummary, reporter.config.Succinct) - } else if specSummary.RunTime.Seconds() >= reporter.config.SlowSpecThreshold { - reporter.stenographer.AnnounceSuccesfulSlowSpec(specSummary, reporter.config.Succinct) - } else { - reporter.stenographer.AnnounceSuccesfulSpec(specSummary) - } - case types.SpecStatePending: - reporter.stenographer.AnnouncePendingSpec(specSummary, reporter.config.NoisyPendings && !reporter.config.Succinct) - case types.SpecStateSkipped: - reporter.stenographer.AnnounceSkippedSpec(specSummary) - case types.SpecStateTimedOut: - reporter.stenographer.AnnounceSpecTimedOut(specSummary, reporter.config.Succinct, reporter.config.FullTrace) - case types.SpecStatePanicked: - reporter.stenographer.AnnounceSpecPanicked(specSummary, reporter.config.Succinct, reporter.config.FullTrace) - case types.SpecStateFailed: - reporter.stenographer.AnnounceSpecFailed(specSummary, reporter.config.Succinct, reporter.config.FullTrace) - } - - reporter.specSummaries = append(reporter.specSummaries, specSummary) -} - -func (reporter *DefaultReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - reporter.stenographer.SummarizeFailures(reporter.specSummaries) - reporter.stenographer.AnnounceSpecRunCompletion(summary, reporter.config.Succinct) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/default_reporter_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/default_reporter_test.go deleted file mode 100644 index 3b719a1..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/default_reporter_test.go +++ /dev/null @@ -1,397 +0,0 @@ -package reporters_test - -import ( - "time" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters" - st "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("DefaultReporter", func() { - var ( - reporter *reporters.DefaultReporter - reporterConfig config.DefaultReporterConfigType - stenographer *st.FakeStenographer - - ginkgoConfig config.GinkgoConfigType - suite *types.SuiteSummary - spec *types.SpecSummary - ) - - BeforeEach(func() { - stenographer = st.NewFakeStenographer() - reporterConfig = config.DefaultReporterConfigType{ - NoColor: false, - SlowSpecThreshold: 0.1, - NoisyPendings: true, - Verbose: true, - FullTrace: true, - } - - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - }) - - call := func(method string, args ...interface{}) st.FakeStenographerCall { - return st.NewFakeStenographerCall(method, args...) - } - - Describe("SpecSuiteWillBegin", func() { - BeforeEach(func() { - suite = &types.SuiteSummary{ - SuiteDescription: "A Sweet Suite", - NumberOfTotalSpecs: 10, - NumberOfSpecsThatWillBeRun: 8, - } - - ginkgoConfig = config.GinkgoConfigType{ - RandomSeed: 1138, - RandomizeAllSpecs: true, - } - }) - - Context("when a serial (non-parallel) suite begins", func() { - BeforeEach(func() { - ginkgoConfig.ParallelTotal = 1 - - reporter.SpecSuiteWillBegin(ginkgoConfig, suite) - }) - - It("should announce the suite, then announce the number of specs", func() { - Ω(stenographer.Calls()).Should(HaveLen(2)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuite", "A Sweet Suite", ginkgoConfig.RandomSeed, true, false))) - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceNumberOfSpecs", 8, 10, false))) - }) - }) - - Context("when a parallel suite begins", func() { - BeforeEach(func() { - ginkgoConfig.ParallelTotal = 2 - ginkgoConfig.ParallelNode = 1 - suite.NumberOfSpecsBeforeParallelization = 20 - - reporter.SpecSuiteWillBegin(ginkgoConfig, suite) - }) - - It("should announce the suite, announce that it's a parallel run, then announce the number of specs", func() { - Ω(stenographer.Calls()).Should(HaveLen(3)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuite", "A Sweet Suite", ginkgoConfig.RandomSeed, true, false))) - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceParallelRun", 1, 2, 10, 20, false))) - Ω(stenographer.Calls()[2]).Should(Equal(call("AnnounceNumberOfSpecs", 8, 10, false))) - }) - }) - }) - - Describe("BeforeSuiteDidRun", func() { - Context("when the BeforeSuite passes", func() { - It("should announce nothing", func() { - reporter.BeforeSuiteDidRun(&types.SetupSummary{ - State: types.SpecStatePassed, - }) - - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("when the BeforeSuite fails", func() { - It("should announce the failure", func() { - summary := &types.SetupSummary{ - State: types.SpecStateFailed, - } - reporter.BeforeSuiteDidRun(summary) - - Ω(stenographer.Calls()).Should(HaveLen(1)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceBeforeSuiteFailure", summary, false, true))) - }) - }) - }) - - Describe("AfterSuiteDidRun", func() { - Context("when the AfterSuite passes", func() { - It("should announce nothing", func() { - reporter.AfterSuiteDidRun(&types.SetupSummary{ - State: types.SpecStatePassed, - }) - - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("when the AfterSuite fails", func() { - It("should announce the failure", func() { - summary := &types.SetupSummary{ - State: types.SpecStateFailed, - } - reporter.AfterSuiteDidRun(summary) - - Ω(stenographer.Calls()).Should(HaveLen(1)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceAfterSuiteFailure", summary, false, true))) - }) - }) - }) - - Describe("SpecWillRun", func() { - Context("When running in verbose mode", func() { - Context("and the spec will run", func() { - BeforeEach(func() { - spec = &types.SpecSummary{} - reporter.SpecWillRun(spec) - }) - - It("should announce that the spec will run", func() { - Ω(stenographer.Calls()).Should(HaveLen(1)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecWillRun", spec))) - }) - }) - - Context("and the spec will not run", func() { - Context("because it is pending", func() { - BeforeEach(func() { - spec = &types.SpecSummary{ - State: types.SpecStatePending, - } - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("because it is skipped", func() { - BeforeEach(func() { - spec = &types.SpecSummary{ - State: types.SpecStateSkipped, - } - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - }) - }) - - Context("When running in verbose & succinct mode", func() { - BeforeEach(func() { - reporterConfig.Succinct = true - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - spec = &types.SpecSummary{} - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("When not running in verbose mode", func() { - BeforeEach(func() { - reporterConfig.Verbose = false - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - spec = &types.SpecSummary{} - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - }) - - Describe("SpecDidComplete", func() { - JustBeforeEach(func() { - reporter.SpecDidComplete(spec) - }) - - BeforeEach(func() { - spec = &types.SpecSummary{} - }) - - Context("When the spec passed", func() { - BeforeEach(func() { - spec.State = types.SpecStatePassed - }) - - Context("When the spec was a measurement", func() { - BeforeEach(func() { - spec.IsMeasurement = true - }) - - It("should announce the measurement", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulMeasurement", spec, false))) - }) - }) - - Context("When the spec is slow", func() { - BeforeEach(func() { - spec.RunTime = time.Second - }) - - It("should announce that it was slow", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSlowSpec", spec, false))) - }) - }) - - Context("Otherwise", func() { - It("should announce the succesful spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSpec", spec))) - }) - }) - }) - - Context("When the spec is pending", func() { - BeforeEach(func() { - spec.State = types.SpecStatePending - }) - - It("should announce the pending spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnouncePendingSpec", spec, true))) - }) - }) - - Context("When the spec is skipped", func() { - BeforeEach(func() { - spec.State = types.SpecStateSkipped - }) - - It("should announce the skipped spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSkippedSpec", spec))) - }) - }) - - Context("When the spec timed out", func() { - BeforeEach(func() { - spec.State = types.SpecStateTimedOut - }) - - It("should announce the timedout spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecTimedOut", spec, false, true))) - }) - }) - - Context("When the spec panicked", func() { - BeforeEach(func() { - spec.State = types.SpecStatePanicked - }) - - It("should announce the panicked spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecPanicked", spec, false, true))) - }) - }) - - Context("When the spec failed", func() { - BeforeEach(func() { - spec.State = types.SpecStateFailed - }) - - It("should announce the failed spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecFailed", spec, false, true))) - }) - }) - - Context("in succinct mode", func() { - BeforeEach(func() { - reporterConfig.Succinct = true - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - }) - - Context("When the spec passed", func() { - BeforeEach(func() { - spec.State = types.SpecStatePassed - }) - - Context("When the spec was a measurement", func() { - BeforeEach(func() { - spec.IsMeasurement = true - }) - - It("should announce the measurement", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulMeasurement", spec, true))) - }) - }) - - Context("When the spec is slow", func() { - BeforeEach(func() { - spec.RunTime = time.Second - }) - - It("should announce that it was slow", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSlowSpec", spec, true))) - }) - }) - - Context("Otherwise", func() { - It("should announce the succesful spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSpec", spec))) - }) - }) - }) - - Context("When the spec is pending", func() { - BeforeEach(func() { - spec.State = types.SpecStatePending - }) - - It("should announce the pending spec, but never noisily", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnouncePendingSpec", spec, false))) - }) - }) - - Context("When the spec is skipped", func() { - BeforeEach(func() { - spec.State = types.SpecStateSkipped - }) - - It("should announce the skipped spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSkippedSpec", spec))) - }) - }) - - Context("When the spec timed out", func() { - BeforeEach(func() { - spec.State = types.SpecStateTimedOut - }) - - It("should announce the timedout spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecTimedOut", spec, true, true))) - }) - }) - - Context("When the spec panicked", func() { - BeforeEach(func() { - spec.State = types.SpecStatePanicked - }) - - It("should announce the panicked spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecPanicked", spec, true, true))) - }) - }) - - Context("When the spec failed", func() { - BeforeEach(func() { - spec.State = types.SpecStateFailed - }) - - It("should announce the failed spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecFailed", spec, true, true))) - }) - }) - }) - }) - - Describe("SpecSuiteDidEnd", func() { - BeforeEach(func() { - suite = &types.SuiteSummary{} - reporter.SpecSuiteDidEnd(suite) - }) - - It("should announce the spec run's completion", func() { - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceSpecRunCompletion", suite, false))) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/fake_reporter.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/fake_reporter.go deleted file mode 100644 index 27db479..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/fake_reporter.go +++ /dev/null @@ -1,59 +0,0 @@ -package reporters - -import ( - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" -) - -//FakeReporter is useful for testing purposes -type FakeReporter struct { - Config config.GinkgoConfigType - - BeginSummary *types.SuiteSummary - BeforeSuiteSummary *types.SetupSummary - SpecWillRunSummaries []*types.SpecSummary - SpecSummaries []*types.SpecSummary - AfterSuiteSummary *types.SetupSummary - EndSummary *types.SuiteSummary - - SpecWillRunStub func(specSummary *types.SpecSummary) - SpecDidCompleteStub func(specSummary *types.SpecSummary) -} - -func NewFakeReporter() *FakeReporter { - return &FakeReporter{ - SpecWillRunSummaries: make([]*types.SpecSummary, 0), - SpecSummaries: make([]*types.SpecSummary, 0), - } -} - -func (fakeR *FakeReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - fakeR.Config = config - fakeR.BeginSummary = summary -} - -func (fakeR *FakeReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - fakeR.BeforeSuiteSummary = setupSummary -} - -func (fakeR *FakeReporter) SpecWillRun(specSummary *types.SpecSummary) { - if fakeR.SpecWillRunStub != nil { - fakeR.SpecWillRunStub(specSummary) - } - fakeR.SpecWillRunSummaries = append(fakeR.SpecWillRunSummaries, specSummary) -} - -func (fakeR *FakeReporter) SpecDidComplete(specSummary *types.SpecSummary) { - if fakeR.SpecDidCompleteStub != nil { - fakeR.SpecDidCompleteStub(specSummary) - } - fakeR.SpecSummaries = append(fakeR.SpecSummaries, specSummary) -} - -func (fakeR *FakeReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - fakeR.AfterSuiteSummary = setupSummary -} - -func (fakeR *FakeReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - fakeR.EndSummary = summary -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/junit_reporter.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/junit_reporter.go deleted file mode 100644 index 278a88e..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/junit_reporter.go +++ /dev/null @@ -1,139 +0,0 @@ -/* - -JUnit XML Reporter for Ginkgo - -For usage instructions: http://onsi.github.io/ginkgo/#generating_junit_xml_output - -*/ - -package reporters - -import ( - "encoding/xml" - "fmt" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" - "os" - "strings" -) - -type JUnitTestSuite struct { - XMLName xml.Name `xml:"testsuite"` - TestCases []JUnitTestCase `xml:"testcase"` - Tests int `xml:"tests,attr"` - Failures int `xml:"failures,attr"` - Time float64 `xml:"time,attr"` -} - -type JUnitTestCase struct { - Name string `xml:"name,attr"` - ClassName string `xml:"classname,attr"` - FailureMessage *JUnitFailureMessage `xml:"failure,omitempty"` - Skipped *JUnitSkipped `xml:"skipped,omitempty"` - Time float64 `xml:"time,attr"` -} - -type JUnitFailureMessage struct { - Type string `xml:"type,attr"` - Message string `xml:",chardata"` -} - -type JUnitSkipped struct { - XMLName xml.Name `xml:"skipped"` -} - -type JUnitReporter struct { - suite JUnitTestSuite - filename string - testSuiteName string -} - -//NewJUnitReporter creates a new JUnit XML reporter. The XML will be stored in the passed in filename. -func NewJUnitReporter(filename string) *JUnitReporter { - return &JUnitReporter{ - filename: filename, - } -} - -func (reporter *JUnitReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - reporter.suite = JUnitTestSuite{ - Tests: summary.NumberOfSpecsThatWillBeRun, - TestCases: []JUnitTestCase{}, - } - reporter.testSuiteName = summary.SuiteDescription -} - -func (reporter *JUnitReporter) SpecWillRun(specSummary *types.SpecSummary) { -} - -func (reporter *JUnitReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - reporter.handleSetupSummary("BeforeSuite", setupSummary) -} - -func (reporter *JUnitReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - reporter.handleSetupSummary("AfterSuite", setupSummary) -} - -func (reporter *JUnitReporter) handleSetupSummary(name string, setupSummary *types.SetupSummary) { - if setupSummary.State != types.SpecStatePassed { - testCase := JUnitTestCase{ - Name: name, - ClassName: reporter.testSuiteName, - } - - testCase.FailureMessage = &JUnitFailureMessage{ - Type: reporter.failureTypeForState(setupSummary.State), - Message: fmt.Sprintf("%s\n%s", setupSummary.Failure.ComponentCodeLocation.String(), setupSummary.Failure.Message), - } - testCase.Time = setupSummary.RunTime.Seconds() - reporter.suite.TestCases = append(reporter.suite.TestCases, testCase) - } -} - -func (reporter *JUnitReporter) SpecDidComplete(specSummary *types.SpecSummary) { - testCase := JUnitTestCase{ - Name: strings.Join(specSummary.ComponentTexts[1:], " "), - ClassName: reporter.testSuiteName, - } - if specSummary.State == types.SpecStateFailed || specSummary.State == types.SpecStateTimedOut || specSummary.State == types.SpecStatePanicked { - testCase.FailureMessage = &JUnitFailureMessage{ - Type: reporter.failureTypeForState(specSummary.State), - Message: fmt.Sprintf("%s\n%s", specSummary.Failure.ComponentCodeLocation.String(), specSummary.Failure.Message), - } - } - if specSummary.State == types.SpecStateSkipped || specSummary.State == types.SpecStatePending { - testCase.Skipped = &JUnitSkipped{} - } - testCase.Time = specSummary.RunTime.Seconds() - reporter.suite.TestCases = append(reporter.suite.TestCases, testCase) -} - -func (reporter *JUnitReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - reporter.suite.Time = summary.RunTime.Seconds() - reporter.suite.Failures = summary.NumberOfFailedSpecs - file, err := os.Create(reporter.filename) - if err != nil { - fmt.Printf("Failed to create JUnit report file: %s\n\t%s", reporter.filename, err.Error()) - } - defer file.Close() - file.WriteString(xml.Header) - encoder := xml.NewEncoder(file) - encoder.Indent(" ", " ") - err = encoder.Encode(reporter.suite) - if err != nil { - fmt.Printf("Failed to generate JUnit report\n\t%s", err.Error()) - } -} - -func (reporter *JUnitReporter) failureTypeForState(state types.SpecState) string { - switch state { - case types.SpecStateFailed: - return "Failure" - case types.SpecStateTimedOut: - return "Timeout" - case types.SpecStatePanicked: - return "Panic" - default: - return "" - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/junit_reporter_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/junit_reporter_test.go deleted file mode 100644 index 744f383..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/junit_reporter_test.go +++ /dev/null @@ -1,241 +0,0 @@ -package reporters_test - -import ( - "encoding/xml" - "io/ioutil" - "os" - "time" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("JUnit Reporter", func() { - var ( - outputFile string - reporter Reporter - ) - - readOutputFile := func() reporters.JUnitTestSuite { - bytes, err := ioutil.ReadFile(outputFile) - Ω(err).ShouldNot(HaveOccurred()) - var suite reporters.JUnitTestSuite - err = xml.Unmarshal(bytes, &suite) - Ω(err).ShouldNot(HaveOccurred()) - return suite - } - - BeforeEach(func() { - f, err := ioutil.TempFile("", "output") - Ω(err).ShouldNot(HaveOccurred()) - f.Close() - outputFile = f.Name() - - reporter = reporters.NewJUnitReporter(outputFile) - - reporter.SpecSuiteWillBegin(config.GinkgoConfigType{}, &types.SuiteSummary{ - SuiteDescription: "My test suite", - NumberOfSpecsThatWillBeRun: 1, - }) - }) - - AfterEach(func() { - os.RemoveAll(outputFile) - }) - - Describe("a passing test", func() { - BeforeEach(func() { - beforeSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - afterSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.AfterSuiteDidRun(afterSuite) - - spec := &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: types.SpecStatePassed, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as passing", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(0)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases).Should(HaveLen(1)) - Ω(output.TestCases[0].Name).Should(Equal("A B C")) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage).Should(BeNil()) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - Ω(output.TestCases[0].Time).Should(Equal(5.0)) - }) - }) - - Describe("when the BeforeSuite fails", func() { - var beforeSuite *types.SetupSummary - - BeforeEach(func() { - beforeSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(1)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("BeforeSuite")) - Ω(output.TestCases[0].Time).Should(Equal(3.0)) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage.Type).Should(Equal("Failure")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring("failed to setup")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(beforeSuite.Failure.ComponentCodeLocation.String())) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - }) - }) - - Describe("when the AfterSuite fails", func() { - var afterSuite *types.SetupSummary - - BeforeEach(func() { - afterSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.AfterSuiteDidRun(afterSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(1)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("AfterSuite")) - Ω(output.TestCases[0].Time).Should(Equal(3.0)) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage.Type).Should(Equal("Failure")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring("failed to setup")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(afterSuite.Failure.ComponentCodeLocation.String())) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - }) - }) - - specStateCases := []struct { - state types.SpecState - message string - }{ - {types.SpecStateFailed, "Failure"}, - {types.SpecStateTimedOut, "Timeout"}, - {types.SpecStatePanicked, "Panic"}, - } - - for _, specStateCase := range specStateCases { - specStateCase := specStateCase - Describe("a failing test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase.state, - RunTime: 5 * time.Second, - Failure: types.SpecFailure{ - ComponentCodeLocation: codelocation.New(0), - Message: "I failed", - }, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as failing", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(1)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("A B C")) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage.Type).Should(Equal(specStateCase.message)) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring("I failed")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(spec.Failure.ComponentCodeLocation.String())) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - }) - }) - } - - for _, specStateCase := range []types.SpecState{types.SpecStatePending, types.SpecStateSkipped} { - specStateCase := specStateCase - Describe("a skipped test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as failing", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(0)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("A B C")) - Ω(output.TestCases[0].Skipped).ShouldNot(BeNil()) - }) - }) - } -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/reporter.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/reporter.go deleted file mode 100644 index 348b9df..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/reporter.go +++ /dev/null @@ -1,15 +0,0 @@ -package reporters - -import ( - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" -) - -type Reporter interface { - SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) - BeforeSuiteDidRun(setupSummary *types.SetupSummary) - SpecWillRun(specSummary *types.SpecSummary) - SpecDidComplete(specSummary *types.SpecSummary) - AfterSuiteDidRun(setupSummary *types.SetupSummary) - SpecSuiteDidEnd(summary *types.SuiteSummary) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/reporters_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/reporters_suite_test.go deleted file mode 100644 index cec5a4d..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/reporters_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package reporters_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestReporters(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Reporters Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/stenographer/console_logging.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/stenographer/console_logging.go deleted file mode 100644 index ce5433a..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/stenographer/console_logging.go +++ /dev/null @@ -1,64 +0,0 @@ -package stenographer - -import ( - "fmt" - "strings" -) - -func (s *consoleStenographer) colorize(colorCode string, format string, args ...interface{}) string { - var out string - - if len(args) > 0 { - out = fmt.Sprintf(format, args...) - } else { - out = format - } - - if s.color { - return fmt.Sprintf("%s%s%s", colorCode, out, defaultStyle) - } else { - return out - } -} - -func (s *consoleStenographer) printBanner(text string, bannerCharacter string) { - fmt.Println(text) - fmt.Println(strings.Repeat(bannerCharacter, len(text))) -} - -func (s *consoleStenographer) printNewLine() { - fmt.Println("") -} - -func (s *consoleStenographer) printDelimiter() { - fmt.Println(s.colorize(grayColor, "%s", strings.Repeat("-", 30))) -} - -func (s *consoleStenographer) print(indentation int, format string, args ...interface{}) { - fmt.Print(s.indent(indentation, format, args...)) -} - -func (s *consoleStenographer) println(indentation int, format string, args ...interface{}) { - fmt.Println(s.indent(indentation, format, args...)) -} - -func (s *consoleStenographer) indent(indentation int, format string, args ...interface{}) string { - var text string - - if len(args) > 0 { - text = fmt.Sprintf(format, args...) - } else { - text = format - } - - stringArray := strings.Split(text, "\n") - padding := "" - if indentation >= 0 { - padding = strings.Repeat(" ", indentation) - } - for i, s := range stringArray { - stringArray[i] = fmt.Sprintf("%s%s", padding, s) - } - - return strings.Join(stringArray, "\n") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/stenographer/fake_stenographer.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/stenographer/fake_stenographer.go deleted file mode 100644 index 3a1e0c2..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/stenographer/fake_stenographer.go +++ /dev/null @@ -1,138 +0,0 @@ -package stenographer - -import ( - "sync" - - "github.com/onsi/ginkgo/types" -) - -func NewFakeStenographerCall(method string, args ...interface{}) FakeStenographerCall { - return FakeStenographerCall{ - Method: method, - Args: args, - } -} - -type FakeStenographer struct { - calls []FakeStenographerCall - lock *sync.Mutex -} - -type FakeStenographerCall struct { - Method string - Args []interface{} -} - -func NewFakeStenographer() *FakeStenographer { - stenographer := &FakeStenographer{ - lock: &sync.Mutex{}, - } - stenographer.Reset() - return stenographer -} - -func (stenographer *FakeStenographer) Calls() []FakeStenographerCall { - stenographer.lock.Lock() - defer stenographer.lock.Unlock() - - return stenographer.calls -} - -func (stenographer *FakeStenographer) Reset() { - stenographer.lock.Lock() - defer stenographer.lock.Unlock() - - stenographer.calls = make([]FakeStenographerCall, 0) -} - -func (stenographer *FakeStenographer) CallsTo(method string) []FakeStenographerCall { - stenographer.lock.Lock() - defer stenographer.lock.Unlock() - - results := make([]FakeStenographerCall, 0) - for _, call := range stenographer.calls { - if call.Method == method { - results = append(results, call) - } - } - - return results -} - -func (stenographer *FakeStenographer) registerCall(method string, args ...interface{}) { - stenographer.lock.Lock() - defer stenographer.lock.Unlock() - - stenographer.calls = append(stenographer.calls, NewFakeStenographerCall(method, args...)) -} - -func (stenographer *FakeStenographer) AnnounceSuite(description string, randomSeed int64, randomizingAll bool, succinct bool) { - stenographer.registerCall("AnnounceSuite", description, randomSeed, randomizingAll, succinct) -} - -func (stenographer *FakeStenographer) AnnounceAggregatedParallelRun(nodes int, succinct bool) { - stenographer.registerCall("AnnounceAggregatedParallelRun", nodes, succinct) -} - -func (stenographer *FakeStenographer) AnnounceParallelRun(node int, nodes int, specsToRun int, totalSpecs int, succinct bool) { - stenographer.registerCall("AnnounceParallelRun", node, nodes, specsToRun, totalSpecs, succinct) -} - -func (stenographer *FakeStenographer) AnnounceNumberOfSpecs(specsToRun int, total int, succinct bool) { - stenographer.registerCall("AnnounceNumberOfSpecs", specsToRun, total, succinct) -} - -func (stenographer *FakeStenographer) AnnounceSpecRunCompletion(summary *types.SuiteSummary, succinct bool) { - stenographer.registerCall("AnnounceSpecRunCompletion", summary, succinct) -} - -func (stenographer *FakeStenographer) AnnounceSpecWillRun(spec *types.SpecSummary) { - stenographer.registerCall("AnnounceSpecWillRun", spec) -} - -func (stenographer *FakeStenographer) AnnounceBeforeSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceBeforeSuiteFailure", summary, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) AnnounceAfterSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceAfterSuiteFailure", summary, succinct, fullTrace) -} -func (stenographer *FakeStenographer) AnnounceCapturedOutput(output string) { - stenographer.registerCall("AnnounceCapturedOutput", output) -} - -func (stenographer *FakeStenographer) AnnounceSuccesfulSpec(spec *types.SpecSummary) { - stenographer.registerCall("AnnounceSuccesfulSpec", spec) -} - -func (stenographer *FakeStenographer) AnnounceSuccesfulSlowSpec(spec *types.SpecSummary, succinct bool) { - stenographer.registerCall("AnnounceSuccesfulSlowSpec", spec, succinct) -} - -func (stenographer *FakeStenographer) AnnounceSuccesfulMeasurement(spec *types.SpecSummary, succinct bool) { - stenographer.registerCall("AnnounceSuccesfulMeasurement", spec, succinct) -} - -func (stenographer *FakeStenographer) AnnouncePendingSpec(spec *types.SpecSummary, noisy bool) { - stenographer.registerCall("AnnouncePendingSpec", spec, noisy) -} - -func (stenographer *FakeStenographer) AnnounceSkippedSpec(spec *types.SpecSummary) { - stenographer.registerCall("AnnounceSkippedSpec", spec) -} - -func (stenographer *FakeStenographer) AnnounceSpecTimedOut(spec *types.SpecSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceSpecTimedOut", spec, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) AnnounceSpecPanicked(spec *types.SpecSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceSpecPanicked", spec, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) AnnounceSpecFailed(spec *types.SpecSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceSpecFailed", spec, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) SummarizeFailures(summaries []*types.SpecSummary) { - stenographer.registerCall("SummarizeFailures", summaries) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go deleted file mode 100644 index d82cdb2..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go +++ /dev/null @@ -1,520 +0,0 @@ -/* -The stenographer is used by Ginkgo's reporters to generate output. - -Move along, nothing to see here. -*/ - -package stenographer - -import ( - "fmt" - "strings" - - "github.com/onsi/ginkgo/types" -) - -const defaultStyle = "\x1b[0m" -const boldStyle = "\x1b[1m" -const redColor = "\x1b[91m" -const greenColor = "\x1b[32m" -const yellowColor = "\x1b[33m" -const cyanColor = "\x1b[36m" -const grayColor = "\x1b[90m" -const lightGrayColor = "\x1b[37m" - -type cursorStateType int - -const ( - cursorStateTop cursorStateType = iota - cursorStateStreaming - cursorStateMidBlock - cursorStateEndBlock -) - -type Stenographer interface { - AnnounceSuite(description string, randomSeed int64, randomizingAll bool, succinct bool) - AnnounceAggregatedParallelRun(nodes int, succinct bool) - AnnounceParallelRun(node int, nodes int, specsToRun int, totalSpecs int, succinct bool) - AnnounceNumberOfSpecs(specsToRun int, total int, succinct bool) - AnnounceSpecRunCompletion(summary *types.SuiteSummary, succinct bool) - - AnnounceSpecWillRun(spec *types.SpecSummary) - AnnounceBeforeSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) - AnnounceAfterSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) - - AnnounceCapturedOutput(output string) - - AnnounceSuccesfulSpec(spec *types.SpecSummary) - AnnounceSuccesfulSlowSpec(spec *types.SpecSummary, succinct bool) - AnnounceSuccesfulMeasurement(spec *types.SpecSummary, succinct bool) - - AnnouncePendingSpec(spec *types.SpecSummary, noisy bool) - AnnounceSkippedSpec(spec *types.SpecSummary) - - AnnounceSpecTimedOut(spec *types.SpecSummary, succinct bool, fullTrace bool) - AnnounceSpecPanicked(spec *types.SpecSummary, succinct bool, fullTrace bool) - AnnounceSpecFailed(spec *types.SpecSummary, succinct bool, fullTrace bool) - - SummarizeFailures(summaries []*types.SpecSummary) -} - -func New(color bool) Stenographer { - return &consoleStenographer{ - color: color, - cursorState: cursorStateTop, - } -} - -type consoleStenographer struct { - color bool - cursorState cursorStateType -} - -var alternatingColors = []string{defaultStyle, grayColor} - -func (s *consoleStenographer) AnnounceSuite(description string, randomSeed int64, randomizingAll bool, succinct bool) { - if succinct { - s.print(0, "[%d] %s ", randomSeed, s.colorize(boldStyle, description)) - return - } - s.printBanner(fmt.Sprintf("Running Suite: %s", description), "=") - s.print(0, "Random Seed: %s", s.colorize(boldStyle, "%d", randomSeed)) - if randomizingAll { - s.print(0, " - Will randomize all specs") - } - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceParallelRun(node int, nodes int, specsToRun int, totalSpecs int, succinct bool) { - if succinct { - s.print(0, "- node #%d ", node) - return - } - s.println(0, - "Parallel test node %s/%s. Assigned %s of %s specs.", - s.colorize(boldStyle, "%d", node), - s.colorize(boldStyle, "%d", nodes), - s.colorize(boldStyle, "%d", specsToRun), - s.colorize(boldStyle, "%d", totalSpecs), - ) - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceAggregatedParallelRun(nodes int, succinct bool) { - if succinct { - s.print(0, "- %d nodes ", nodes) - return - } - s.println(0, - "Running in parallel across %s nodes", - s.colorize(boldStyle, "%d", nodes), - ) - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceNumberOfSpecs(specsToRun int, total int, succinct bool) { - if succinct { - s.print(0, "- %d/%d specs ", specsToRun, total) - s.stream() - return - } - s.println(0, - "Will run %s of %s specs", - s.colorize(boldStyle, "%d", specsToRun), - s.colorize(boldStyle, "%d", total), - ) - - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceSpecRunCompletion(summary *types.SuiteSummary, succinct bool) { - if succinct && summary.SuiteSucceeded { - s.print(0, " %s %s ", s.colorize(greenColor, "SUCCESS!"), summary.RunTime) - return - } - s.printNewLine() - color := greenColor - if !summary.SuiteSucceeded { - color = redColor - } - s.println(0, s.colorize(boldStyle+color, "Ran %d of %d Specs in %.3f seconds", summary.NumberOfSpecsThatWillBeRun, summary.NumberOfTotalSpecs, summary.RunTime.Seconds())) - - status := "" - if summary.SuiteSucceeded { - status = s.colorize(boldStyle+greenColor, "SUCCESS!") - } else { - status = s.colorize(boldStyle+redColor, "FAIL!") - } - - s.print(0, - "%s -- %s | %s | %s | %s ", - status, - s.colorize(greenColor+boldStyle, "%d Passed", summary.NumberOfPassedSpecs), - s.colorize(redColor+boldStyle, "%d Failed", summary.NumberOfFailedSpecs), - s.colorize(yellowColor+boldStyle, "%d Pending", summary.NumberOfPendingSpecs), - s.colorize(cyanColor+boldStyle, "%d Skipped", summary.NumberOfSkippedSpecs), - ) -} - -func (s *consoleStenographer) AnnounceSpecWillRun(spec *types.SpecSummary) { - s.startBlock() - for i, text := range spec.ComponentTexts[1 : len(spec.ComponentTexts)-1] { - s.print(0, s.colorize(alternatingColors[i%2], text)+" ") - } - - indentation := 0 - if len(spec.ComponentTexts) > 2 { - indentation = 1 - s.printNewLine() - } - index := len(spec.ComponentTexts) - 1 - s.print(indentation, s.colorize(boldStyle, spec.ComponentTexts[index])) - s.printNewLine() - s.print(indentation, s.colorize(lightGrayColor, spec.ComponentCodeLocations[index].String())) - s.printNewLine() - s.midBlock() -} - -func (s *consoleStenographer) AnnounceBeforeSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) { - s.announceSetupFailure("BeforeSuite", summary, succinct, fullTrace) -} - -func (s *consoleStenographer) AnnounceAfterSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) { - s.announceSetupFailure("AfterSuite", summary, succinct, fullTrace) -} - -func (s *consoleStenographer) announceSetupFailure(name string, summary *types.SetupSummary, succinct bool, fullTrace bool) { - s.startBlock() - var message string - switch summary.State { - case types.SpecStateFailed: - message = "Failure" - case types.SpecStatePanicked: - message = "Panic" - case types.SpecStateTimedOut: - message = "Timeout" - } - - s.println(0, s.colorize(redColor+boldStyle, "%s [%.3f seconds]", message, summary.RunTime.Seconds())) - - indentation := s.printCodeLocationBlock([]string{name}, []types.CodeLocation{summary.CodeLocation}, summary.ComponentType, 0, true, true) - - s.printNewLine() - s.printFailure(indentation, summary.State, summary.Failure, fullTrace) - - s.endBlock() -} - -func (s *consoleStenographer) AnnounceCapturedOutput(output string) { - if output == "" { - return - } - - s.startBlock() - s.println(0, output) - s.midBlock() -} - -func (s *consoleStenographer) AnnounceSuccesfulSpec(spec *types.SpecSummary) { - s.print(0, s.colorize(greenColor, "•")) - s.stream() -} - -func (s *consoleStenographer) AnnounceSuccesfulSlowSpec(spec *types.SpecSummary, succinct bool) { - s.printBlockWithMessage( - s.colorize(greenColor, "• [SLOW TEST:%.3f seconds]", spec.RunTime.Seconds()), - "", - spec, - succinct, - ) -} - -func (s *consoleStenographer) AnnounceSuccesfulMeasurement(spec *types.SpecSummary, succinct bool) { - s.printBlockWithMessage( - s.colorize(greenColor, "• [MEASUREMENT]"), - s.measurementReport(spec, succinct), - spec, - succinct, - ) -} - -func (s *consoleStenographer) AnnouncePendingSpec(spec *types.SpecSummary, noisy bool) { - if noisy { - s.printBlockWithMessage( - s.colorize(yellowColor, "P [PENDING]"), - "", - spec, - false, - ) - } else { - s.print(0, s.colorize(yellowColor, "P")) - s.stream() - } -} - -func (s *consoleStenographer) AnnounceSkippedSpec(spec *types.SpecSummary) { - s.print(0, s.colorize(cyanColor, "S")) - s.stream() -} - -func (s *consoleStenographer) AnnounceSpecTimedOut(spec *types.SpecSummary, succinct bool, fullTrace bool) { - s.printSpecFailure("•... Timeout", spec, succinct, fullTrace) -} - -func (s *consoleStenographer) AnnounceSpecPanicked(spec *types.SpecSummary, succinct bool, fullTrace bool) { - s.printSpecFailure("•! Panic", spec, succinct, fullTrace) -} - -func (s *consoleStenographer) AnnounceSpecFailed(spec *types.SpecSummary, succinct bool, fullTrace bool) { - s.printSpecFailure("• Failure", spec, succinct, fullTrace) -} - -func (s *consoleStenographer) SummarizeFailures(summaries []*types.SpecSummary) { - failingSpecs := []*types.SpecSummary{} - - for _, summary := range summaries { - if summary.HasFailureState() { - failingSpecs = append(failingSpecs, summary) - } - } - - if len(failingSpecs) == 0 { - return - } - - s.printNewLine() - s.printNewLine() - plural := "s" - if len(failingSpecs) == 1 { - plural = "" - } - s.println(0, s.colorize(redColor+boldStyle, "Summarizing %d Failure%s:", len(failingSpecs), plural)) - for _, summary := range failingSpecs { - s.printNewLine() - if summary.HasFailureState() { - if summary.TimedOut() { - s.print(0, s.colorize(redColor+boldStyle, "[Timeout...] ")) - } else if summary.Panicked() { - s.print(0, s.colorize(redColor+boldStyle, "[Panic!] ")) - } else if summary.Failed() { - s.print(0, s.colorize(redColor+boldStyle, "[Fail] ")) - } - s.printSpecContext(summary.ComponentTexts, summary.ComponentCodeLocations, summary.Failure.ComponentType, summary.Failure.ComponentIndex, true, true) - s.printNewLine() - s.println(0, s.colorize(lightGrayColor, summary.Failure.Location.String())) - } - } -} - -func (s *consoleStenographer) startBlock() { - if s.cursorState == cursorStateStreaming { - s.printNewLine() - s.printDelimiter() - } else if s.cursorState == cursorStateMidBlock { - s.printNewLine() - } -} - -func (s *consoleStenographer) midBlock() { - s.cursorState = cursorStateMidBlock -} - -func (s *consoleStenographer) endBlock() { - s.printDelimiter() - s.cursorState = cursorStateEndBlock -} - -func (s *consoleStenographer) stream() { - s.cursorState = cursorStateStreaming -} - -func (s *consoleStenographer) printBlockWithMessage(header string, message string, spec *types.SpecSummary, succinct bool) { - s.startBlock() - s.println(0, header) - - indentation := s.printCodeLocationBlock(spec.ComponentTexts, spec.ComponentCodeLocations, types.SpecComponentTypeInvalid, 0, false, succinct) - - if message != "" { - s.printNewLine() - s.println(indentation, message) - } - - s.endBlock() -} - -func (s *consoleStenographer) printSpecFailure(message string, spec *types.SpecSummary, succinct bool, fullTrace bool) { - s.startBlock() - s.println(0, s.colorize(redColor+boldStyle, "%s%s [%.3f seconds]", message, s.failureContext(spec.Failure.ComponentType), spec.RunTime.Seconds())) - - indentation := s.printCodeLocationBlock(spec.ComponentTexts, spec.ComponentCodeLocations, spec.Failure.ComponentType, spec.Failure.ComponentIndex, true, succinct) - - s.printNewLine() - s.printFailure(indentation, spec.State, spec.Failure, fullTrace) - s.endBlock() -} - -func (s *consoleStenographer) failureContext(failedComponentType types.SpecComponentType) string { - switch failedComponentType { - case types.SpecComponentTypeBeforeSuite: - return " in Suite Setup (BeforeSuite)" - case types.SpecComponentTypeAfterSuite: - return " in Suite Teardown (AfterSuite)" - case types.SpecComponentTypeBeforeEach: - return " in Spec Setup (BeforeEach)" - case types.SpecComponentTypeJustBeforeEach: - return " in Spec Setup (JustBeforeEach)" - case types.SpecComponentTypeAfterEach: - return " in Spec Teardown (AfterEach)" - } - - return "" -} - -func (s *consoleStenographer) printFailure(indentation int, state types.SpecState, failure types.SpecFailure, fullTrace bool) { - if state == types.SpecStatePanicked { - s.println(indentation, s.colorize(redColor+boldStyle, failure.Message)) - s.println(indentation, s.colorize(redColor, failure.ForwardedPanic)) - s.println(indentation, failure.Location.String()) - s.printNewLine() - s.println(indentation, s.colorize(redColor, "Full Stack Trace")) - s.println(indentation, failure.Location.FullStackTrace) - } else { - s.println(indentation, s.colorize(redColor, failure.Message)) - s.printNewLine() - s.println(indentation, failure.Location.String()) - if fullTrace { - s.printNewLine() - s.println(indentation, s.colorize(redColor, "Full Stack Trace")) - s.println(indentation, failure.Location.FullStackTrace) - } - } -} - -func (s *consoleStenographer) printSpecContext(componentTexts []string, componentCodeLocations []types.CodeLocation, failedComponentType types.SpecComponentType, failedComponentIndex int, failure bool, succinct bool) int { - startIndex := 1 - indentation := 0 - - if len(componentTexts) == 1 { - startIndex = 0 - } - - for i := startIndex; i < len(componentTexts); i++ { - if failure && i == failedComponentIndex { - blockType := "" - switch failedComponentType { - case types.SpecComponentTypeBeforeSuite: - blockType = "BeforeSuite" - case types.SpecComponentTypeAfterSuite: - blockType = "AfterSuite" - case types.SpecComponentTypeBeforeEach: - blockType = "BeforeEach" - case types.SpecComponentTypeJustBeforeEach: - blockType = "JustBeforeEach" - case types.SpecComponentTypeAfterEach: - blockType = "AfterEach" - case types.SpecComponentTypeIt: - blockType = "It" - case types.SpecComponentTypeMeasure: - blockType = "Measurement" - } - if succinct { - s.print(0, s.colorize(redColor+boldStyle, "[%s] %s ", blockType, componentTexts[i])) - } else { - s.println(indentation, s.colorize(redColor+boldStyle, "%s [%s]", componentTexts[i], blockType)) - s.println(indentation, s.colorize(grayColor, "%s", componentCodeLocations[i])) - } - } else { - if succinct { - s.print(0, s.colorize(alternatingColors[i%2], "%s ", componentTexts[i])) - } else { - s.println(indentation, componentTexts[i]) - s.println(indentation, s.colorize(grayColor, "%s", componentCodeLocations[i])) - } - } - indentation++ - } - - return indentation -} - -func (s *consoleStenographer) printCodeLocationBlock(componentTexts []string, componentCodeLocations []types.CodeLocation, failedComponentType types.SpecComponentType, failedComponentIndex int, failure bool, succinct bool) int { - indentation := s.printSpecContext(componentTexts, componentCodeLocations, failedComponentType, failedComponentIndex, failure, succinct) - - if succinct { - if len(componentTexts) > 0 { - s.printNewLine() - s.print(0, s.colorize(lightGrayColor, "%s", componentCodeLocations[len(componentCodeLocations)-1])) - } - s.printNewLine() - indentation = 1 - } else { - indentation-- - } - - return indentation -} - -func (s *consoleStenographer) orderedMeasurementKeys(measurements map[string]*types.SpecMeasurement) []string { - orderedKeys := make([]string, len(measurements)) - for key, measurement := range measurements { - orderedKeys[measurement.Order] = key - } - return orderedKeys -} - -func (s *consoleStenographer) measurementReport(spec *types.SpecSummary, succinct bool) string { - if len(spec.Measurements) == 0 { - return "Found no measurements" - } - - message := []string{} - orderedKeys := s.orderedMeasurementKeys(spec.Measurements) - - if succinct { - message = append(message, fmt.Sprintf("%s samples:", s.colorize(boldStyle, "%d", spec.NumberOfSamples))) - for _, key := range orderedKeys { - measurement := spec.Measurements[key] - message = append(message, fmt.Sprintf(" %s - %s: %s%s, %s: %s%s ± %s%s, %s: %s%s", - s.colorize(boldStyle, "%s", measurement.Name), - measurement.SmallestLabel, - s.colorize(greenColor, "%.3f", measurement.Smallest), - measurement.Units, - measurement.AverageLabel, - s.colorize(cyanColor, "%.3f", measurement.Average), - measurement.Units, - s.colorize(cyanColor, "%.3f", measurement.StdDeviation), - measurement.Units, - measurement.LargestLabel, - s.colorize(redColor, "%.3f", measurement.Largest), - measurement.Units, - )) - } - } else { - message = append(message, fmt.Sprintf("Ran %s samples:", s.colorize(boldStyle, "%d", spec.NumberOfSamples))) - for _, key := range orderedKeys { - measurement := spec.Measurements[key] - info := "" - if measurement.Info != nil { - message = append(message, fmt.Sprintf("%v", measurement.Info)) - } - - message = append(message, fmt.Sprintf("%s:\n%s %s: %s%s\n %s: %s%s\n %s: %s%s ± %s%s", - s.colorize(boldStyle, "%s", measurement.Name), - info, - measurement.SmallestLabel, - s.colorize(greenColor, "%.3f", measurement.Smallest), - measurement.Units, - measurement.LargestLabel, - s.colorize(redColor, "%.3f", measurement.Largest), - measurement.Units, - measurement.AverageLabel, - s.colorize(cyanColor, "%.3f", measurement.Average), - measurement.Units, - s.colorize(cyanColor, "%.3f", measurement.StdDeviation), - measurement.Units, - )) - } - } - - return strings.Join(message, "\n") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/teamcity_reporter.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/teamcity_reporter.go deleted file mode 100644 index 657dfe7..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/teamcity_reporter.go +++ /dev/null @@ -1,92 +0,0 @@ -/* - -TeamCity Reporter for Ginkgo - -Makes use of TeamCity's support for Service Messages -http://confluence.jetbrains.com/display/TCD7/Build+Script+Interaction+with+TeamCity#BuildScriptInteractionwithTeamCity-ReportingTests -*/ - -package reporters - -import ( - "fmt" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" - "io" - "strings" -) - -const ( - messageId = "##teamcity" -) - -type TeamCityReporter struct { - writer io.Writer - testSuiteName string -} - -func NewTeamCityReporter(writer io.Writer) *TeamCityReporter { - return &TeamCityReporter{ - writer: writer, - } -} - -func (reporter *TeamCityReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - reporter.testSuiteName = escape(summary.SuiteDescription) - fmt.Fprintf(reporter.writer, "%s[testSuiteStarted name='%s']", messageId, reporter.testSuiteName) -} - -func (reporter *TeamCityReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - reporter.handleSetupSummary("BeforeSuite", setupSummary) -} - -func (reporter *TeamCityReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - reporter.handleSetupSummary("AfterSuite", setupSummary) -} - -func (reporter *TeamCityReporter) handleSetupSummary(name string, setupSummary *types.SetupSummary) { - if setupSummary.State != types.SpecStatePassed { - testName := escape(name) - fmt.Fprintf(reporter.writer, "%s[testStarted name='%s']", messageId, testName) - message := escape(setupSummary.Failure.ComponentCodeLocation.String()) - details := escape(setupSummary.Failure.Message) - fmt.Fprintf(reporter.writer, "%s[testFailed name='%s' message='%s' details='%s']", messageId, testName, message, details) - durationInMilliseconds := setupSummary.RunTime.Seconds() * 1000 - fmt.Fprintf(reporter.writer, "%s[testFinished name='%s' duration='%v']", messageId, testName, durationInMilliseconds) - } -} - -func (reporter *TeamCityReporter) SpecWillRun(specSummary *types.SpecSummary) { - testName := escape(strings.Join(specSummary.ComponentTexts[1:], " ")) - fmt.Fprintf(reporter.writer, "%s[testStarted name='%s']", messageId, testName) -} - -func (reporter *TeamCityReporter) SpecDidComplete(specSummary *types.SpecSummary) { - testName := escape(strings.Join(specSummary.ComponentTexts[1:], " ")) - - if specSummary.State == types.SpecStateFailed || specSummary.State == types.SpecStateTimedOut || specSummary.State == types.SpecStatePanicked { - message := escape(specSummary.Failure.ComponentCodeLocation.String()) - details := escape(specSummary.Failure.Message) - fmt.Fprintf(reporter.writer, "%s[testFailed name='%s' message='%s' details='%s']", messageId, testName, message, details) - } - if specSummary.State == types.SpecStateSkipped || specSummary.State == types.SpecStatePending { - fmt.Fprintf(reporter.writer, "%s[testIgnored name='%s']", messageId, testName) - } - - durationInMilliseconds := specSummary.RunTime.Seconds() * 1000 - fmt.Fprintf(reporter.writer, "%s[testFinished name='%s' duration='%v']", messageId, testName, durationInMilliseconds) -} - -func (reporter *TeamCityReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - fmt.Fprintf(reporter.writer, "%s[testSuiteFinished name='%s']", messageId, reporter.testSuiteName) -} - -func escape(output string) string { - output = strings.Replace(output, "|", "||", -1) - output = strings.Replace(output, "'", "|'", -1) - output = strings.Replace(output, "\n", "|n", -1) - output = strings.Replace(output, "\r", "|r", -1) - output = strings.Replace(output, "[", "|[", -1) - output = strings.Replace(output, "]", "|]", -1) - return output -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go deleted file mode 100644 index de87732..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package reporters_test - -import ( - "bytes" - "fmt" - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "time" -) - -var _ = Describe("TeamCity Reporter", func() { - var ( - buffer bytes.Buffer - reporter Reporter - ) - - BeforeEach(func() { - buffer.Truncate(0) - reporter = reporters.NewTeamCityReporter(&buffer) - reporter.SpecSuiteWillBegin(config.GinkgoConfigType{}, &types.SuiteSummary{ - SuiteDescription: "Foo's test suite", - NumberOfSpecsThatWillBeRun: 1, - }) - }) - - Describe("a passing test", func() { - BeforeEach(func() { - beforeSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - afterSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.AfterSuiteDidRun(afterSuite) - - spec := &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: types.SpecStatePassed, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as passing", func() { - actual := buffer.String() - expected := - "##teamcity[testSuiteStarted name='Foo|'s test suite']" + - "##teamcity[testStarted name='A B C']" + - "##teamcity[testFinished name='A B C' duration='5000']" + - "##teamcity[testSuiteFinished name='Foo|'s test suite']" - Ω(actual).Should(Equal(expected)) - }) - }) - - Describe("when the BeforeSuite fails", func() { - var beforeSuite *types.SetupSummary - - BeforeEach(func() { - beforeSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup\n", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - actual := buffer.String() - expected := fmt.Sprintf( - "##teamcity[testSuiteStarted name='Foo|'s test suite']"+ - "##teamcity[testStarted name='BeforeSuite']"+ - "##teamcity[testFailed name='BeforeSuite' message='%s' details='failed to setup|n']"+ - "##teamcity[testFinished name='BeforeSuite' duration='3000']"+ - "##teamcity[testSuiteFinished name='Foo|'s test suite']", beforeSuite.Failure.ComponentCodeLocation.String(), - ) - Ω(actual).Should(Equal(expected)) - }) - }) - - Describe("when the AfterSuite fails", func() { - var afterSuite *types.SetupSummary - - BeforeEach(func() { - afterSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup\n", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.AfterSuiteDidRun(afterSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - actual := buffer.String() - expected := fmt.Sprintf( - "##teamcity[testSuiteStarted name='Foo|'s test suite']"+ - "##teamcity[testStarted name='AfterSuite']"+ - "##teamcity[testFailed name='AfterSuite' message='%s' details='failed to setup|n']"+ - "##teamcity[testFinished name='AfterSuite' duration='3000']"+ - "##teamcity[testSuiteFinished name='Foo|'s test suite']", afterSuite.Failure.ComponentCodeLocation.String(), - ) - Ω(actual).Should(Equal(expected)) - }) - }) - specStateCases := []struct { - state types.SpecState - message string - }{ - {types.SpecStateFailed, "Failure"}, - {types.SpecStateTimedOut, "Timeout"}, - {types.SpecStatePanicked, "Panic"}, - } - - for _, specStateCase := range specStateCases { - specStateCase := specStateCase - Describe("a failing test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase.state, - RunTime: 5 * time.Second, - Failure: types.SpecFailure{ - ComponentCodeLocation: codelocation.New(0), - Message: "I failed", - }, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as failing", func() { - actual := buffer.String() - expected := - fmt.Sprintf("##teamcity[testSuiteStarted name='Foo|'s test suite']"+ - "##teamcity[testStarted name='A B C']"+ - "##teamcity[testFailed name='A B C' message='%s' details='I failed']"+ - "##teamcity[testFinished name='A B C' duration='5000']"+ - "##teamcity[testSuiteFinished name='Foo|'s test suite']", spec.Failure.ComponentCodeLocation.String()) - Ω(actual).Should(Equal(expected)) - }) - }) - } - - for _, specStateCase := range []types.SpecState{types.SpecStatePending, types.SpecStateSkipped} { - specStateCase := specStateCase - Describe("a skipped test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as ignored", func() { - actual := buffer.String() - expected := - "##teamcity[testSuiteStarted name='Foo|'s test suite']" + - "##teamcity[testStarted name='A B C']" + - "##teamcity[testIgnored name='A B C']" + - "##teamcity[testFinished name='A B C' duration='5000']" + - "##teamcity[testSuiteFinished name='Foo|'s test suite']" - Ω(actual).Should(Equal(expected)) - }) - }) - } -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/code_location.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/types/code_location.go deleted file mode 100644 index 935a89e..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/code_location.go +++ /dev/null @@ -1,15 +0,0 @@ -package types - -import ( - "fmt" -) - -type CodeLocation struct { - FileName string - LineNumber int - FullStackTrace string -} - -func (codeLocation CodeLocation) String() string { - return fmt.Sprintf("%s:%d", codeLocation.FileName, codeLocation.LineNumber) -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/synchronization.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/types/synchronization.go deleted file mode 100644 index fdd6ed5..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/synchronization.go +++ /dev/null @@ -1,30 +0,0 @@ -package types - -import ( - "encoding/json" -) - -type RemoteBeforeSuiteState int - -const ( - RemoteBeforeSuiteStateInvalid RemoteBeforeSuiteState = iota - - RemoteBeforeSuiteStatePending - RemoteBeforeSuiteStatePassed - RemoteBeforeSuiteStateFailed - RemoteBeforeSuiteStateDisappeared -) - -type RemoteBeforeSuiteData struct { - Data []byte - State RemoteBeforeSuiteState -} - -func (r RemoteBeforeSuiteData) ToJSON() []byte { - data, _ := json.Marshal(r) - return data -} - -type RemoteAfterSuiteData struct { - CanRun bool -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types.go deleted file mode 100644 index 583b347..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types.go +++ /dev/null @@ -1,139 +0,0 @@ -package types - -import "time" - -const GINKGO_FOCUS_EXIT_CODE = 197 - -type SuiteSummary struct { - SuiteDescription string - SuiteSucceeded bool - SuiteID string - - NumberOfSpecsBeforeParallelization int - NumberOfTotalSpecs int - NumberOfSpecsThatWillBeRun int - NumberOfPendingSpecs int - NumberOfSkippedSpecs int - NumberOfPassedSpecs int - NumberOfFailedSpecs int - RunTime time.Duration -} - -type SpecSummary struct { - ComponentTexts []string - ComponentCodeLocations []CodeLocation - - State SpecState - RunTime time.Duration - Failure SpecFailure - IsMeasurement bool - NumberOfSamples int - Measurements map[string]*SpecMeasurement - - CapturedOutput string - SuiteID string -} - -func (s SpecSummary) HasFailureState() bool { - return s.State == SpecStateTimedOut || s.State == SpecStatePanicked || s.State == SpecStateFailed -} - -func (s SpecSummary) TimedOut() bool { - return s.State == SpecStateTimedOut -} - -func (s SpecSummary) Panicked() bool { - return s.State == SpecStatePanicked -} - -func (s SpecSummary) Failed() bool { - return s.State == SpecStateFailed -} - -func (s SpecSummary) Passed() bool { - return s.State == SpecStatePassed -} - -func (s SpecSummary) Skipped() bool { - return s.State == SpecStateSkipped -} - -func (s SpecSummary) Pending() bool { - return s.State == SpecStatePending -} - -type SetupSummary struct { - ComponentType SpecComponentType - CodeLocation CodeLocation - - State SpecState - RunTime time.Duration - Failure SpecFailure - - CapturedOutput string - SuiteID string -} - -type SpecFailure struct { - Message string - Location CodeLocation - ForwardedPanic string - - ComponentIndex int - ComponentType SpecComponentType - ComponentCodeLocation CodeLocation -} - -type SpecMeasurement struct { - Name string - Info interface{} - Order int - - Results []float64 - - Smallest float64 - Largest float64 - Average float64 - StdDeviation float64 - - SmallestLabel string - LargestLabel string - AverageLabel string - Units string -} - -type SpecState uint - -const ( - SpecStateInvalid SpecState = iota - - SpecStatePending - SpecStateSkipped - SpecStatePassed - SpecStateFailed - SpecStatePanicked - SpecStateTimedOut -) - -type SpecComponentType uint - -const ( - SpecComponentTypeInvalid SpecComponentType = iota - - SpecComponentTypeContainer - SpecComponentTypeBeforeSuite - SpecComponentTypeAfterSuite - SpecComponentTypeBeforeEach - SpecComponentTypeJustBeforeEach - SpecComponentTypeAfterEach - SpecComponentTypeIt - SpecComponentTypeMeasure -) - -type FlagType uint - -const ( - FlagTypeNone FlagType = iota - FlagTypeFocused - FlagTypePending -) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_suite_test.go deleted file mode 100644 index b026169..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package types_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestTypes(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Types Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_test.go deleted file mode 100644 index 124b216..0000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package types_test - -import ( - . "github.com/onsi/ginkgo/types" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var specStates = []SpecState{ - SpecStatePassed, - SpecStateTimedOut, - SpecStatePanicked, - SpecStateFailed, - SpecStatePending, - SpecStateSkipped, -} - -func verifySpecSummary(caller func(SpecSummary) bool, trueStates ...SpecState) { - summary := SpecSummary{} - trueStateLookup := map[SpecState]bool{} - for _, state := range trueStates { - trueStateLookup[state] = true - summary.State = state - Ω(caller(summary)).Should(BeTrue()) - } - - for _, state := range specStates { - if trueStateLookup[state] { - continue - } - summary.State = state - Ω(caller(summary)).Should(BeFalse()) - } -} - -var _ = Describe("Types", func() { - Describe("SpecSummary", func() { - It("knows when it is in a failure-like state", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.HasFailureState() - }, SpecStateTimedOut, SpecStatePanicked, SpecStateFailed) - }) - - It("knows when it passed", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Passed() - }, SpecStatePassed) - }) - - It("knows when it has failed", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Failed() - }, SpecStateFailed) - }) - - It("knows when it has panicked", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Panicked() - }, SpecStatePanicked) - }) - - It("knows when it has timed out", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.TimedOut() - }, SpecStateTimedOut) - }) - - It("knows when it is pending", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Pending() - }, SpecStatePending) - }) - - It("knows when it is skipped", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Skipped() - }, SpecStateSkipped) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/format/format.go b/Godeps/_workspace/src/github.com/onsi/gomega/format/format.go deleted file mode 100644 index ec9c91a..0000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/format/format.go +++ /dev/null @@ -1,276 +0,0 @@ -/* -Gomega's format package pretty-prints objects. It explores input objects recursively and generates formatted, indented output with type information. -*/ -package format - -import ( - "fmt" - "reflect" - "strings" -) - -// Use MaxDepth to set the maximum recursion depth when printing deeply nested objects -var MaxDepth = uint(10) - -/* -By default, all objects (even those that implement fmt.Stringer and fmt.GoStringer) are recursively inspected to generate output. - -Set UseStringerRepresentation = true to use GoString (for fmt.GoStringers) or String (for fmt.Stringer) instead. - -Note that GoString and String don't always have all the information you need to understand why a test failed! -*/ -var UseStringerRepresentation = false - -//The default indentation string emitted by the format package -var Indent = " " - -var longFormThreshold = 20 - -/* -Generates a formatted matcher success/failure message of the form: - - Expected - - - - -If expected is omited, then the message looks like: - - Expected - - -*/ -func Message(actual interface{}, message string, expected ...interface{}) string { - if len(expected) == 0 { - return fmt.Sprintf("Expected\n%s\n%s", Object(actual, 1), message) - } else { - return fmt.Sprintf("Expected\n%s\n%s\n%s", Object(actual, 1), message, Object(expected[0], 1)) - } -} - -/* -Pretty prints the passed in object at the passed in indentation level. - -Object recurses into deeply nested objects emitting pretty-printed representations of their components. - -Modify format.MaxDepth to control how deep the recursion is allowed to go -Set format.UseStringerRepresentation to true to return object.GoString() or object.String() when available instead of -recursing into the object. -*/ -func Object(object interface{}, indentation uint) string { - indent := strings.Repeat(Indent, int(indentation)) - value := reflect.ValueOf(object) - return fmt.Sprintf("%s<%s>: %s", indent, formatType(object), formatValue(value, indentation)) -} - -/* -IndentString takes a string and indents each line by the specified amount. -*/ -func IndentString(s string, indentation uint) string { - components := strings.Split(s, "\n") - result := "" - indent := strings.Repeat(Indent, int(indentation)) - for i, component := range components { - result += indent + component - if i < len(components)-1 { - result += "\n" - } - } - - return result -} - -func formatType(object interface{}) string { - t := reflect.TypeOf(object) - if t == nil { - return "nil" - } - switch t.Kind() { - case reflect.Chan: - v := reflect.ValueOf(object) - return fmt.Sprintf("%T | len:%d, cap:%d", object, v.Len(), v.Cap()) - case reflect.Ptr: - return fmt.Sprintf("%T | %p", object, object) - case reflect.Slice: - v := reflect.ValueOf(object) - return fmt.Sprintf("%T | len:%d, cap:%d", object, v.Len(), v.Cap()) - case reflect.Map: - v := reflect.ValueOf(object) - return fmt.Sprintf("%T | len:%d", object, v.Len()) - default: - return fmt.Sprintf("%T", object) - } -} - -func formatValue(value reflect.Value, indentation uint) string { - if indentation > MaxDepth { - return "..." - } - - if isNilValue(value) { - return "nil" - } - - if UseStringerRepresentation { - if value.CanInterface() { - obj := value.Interface() - switch x := obj.(type) { - case fmt.GoStringer: - return x.GoString() - case fmt.Stringer: - return x.String() - } - } - } - - switch value.Kind() { - case reflect.Bool: - return fmt.Sprintf("%v", value.Bool()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return fmt.Sprintf("%v", value.Int()) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return fmt.Sprintf("%v", value.Uint()) - case reflect.Uintptr: - return fmt.Sprintf("0x%x", value.Uint()) - case reflect.Float32, reflect.Float64: - return fmt.Sprintf("%v", value.Float()) - case reflect.Complex64, reflect.Complex128: - return fmt.Sprintf("%v", value.Complex()) - case reflect.Chan: - return fmt.Sprintf("0x%x", value.Pointer()) - case reflect.Func: - return fmt.Sprintf("0x%x", value.Pointer()) - case reflect.Ptr: - return formatValue(value.Elem(), indentation) - case reflect.Slice: - if value.Type().Elem().Kind() == reflect.Uint8 { - return formatString(value.Bytes(), indentation) - } - return formatSlice(value, indentation) - case reflect.String: - return formatString(value.String(), indentation) - case reflect.Array: - return formatSlice(value, indentation) - case reflect.Map: - return formatMap(value, indentation) - case reflect.Struct: - return formatStruct(value, indentation) - case reflect.Interface: - return formatValue(value.Elem(), indentation) - default: - if value.CanInterface() { - return fmt.Sprintf("%#v", value.Interface()) - } else { - return fmt.Sprintf("%#v", value) - } - } -} - -func formatString(object interface{}, indentation uint) string { - if indentation == 1 { - s := fmt.Sprintf("%s", object) - components := strings.Split(s, "\n") - result := "" - for i, component := range components { - if i == 0 { - result += component - } else { - result += Indent + component - } - if i < len(components)-1 { - result += "\n" - } - } - - return fmt.Sprintf("%s", result) - } else { - return fmt.Sprintf("%q", object) - } -} - -func formatSlice(v reflect.Value, indentation uint) string { - l := v.Len() - result := make([]string, l) - longest := 0 - for i := 0; i < l; i++ { - result[i] = formatValue(v.Index(i), indentation+1) - if len(result[i]) > longest { - longest = len(result[i]) - } - } - - if longest > longFormThreshold { - indenter := strings.Repeat(Indent, int(indentation)) - return fmt.Sprintf("[\n%s%s,\n%s]", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) - } else { - return fmt.Sprintf("[%s]", strings.Join(result, ", ")) - } -} - -func formatMap(v reflect.Value, indentation uint) string { - l := v.Len() - result := make([]string, l) - - longest := 0 - for i, key := range v.MapKeys() { - value := v.MapIndex(key) - result[i] = fmt.Sprintf("%s: %s", formatValue(key, 0), formatValue(value, indentation+1)) - if len(result[i]) > longest { - longest = len(result[i]) - } - } - - if longest > longFormThreshold { - indenter := strings.Repeat(Indent, int(indentation)) - return fmt.Sprintf("{\n%s%s,\n%s}", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) - } else { - return fmt.Sprintf("{%s}", strings.Join(result, ", ")) - } -} - -func formatStruct(v reflect.Value, indentation uint) string { - t := v.Type() - - l := v.NumField() - result := []string{} - longest := 0 - for i := 0; i < l; i++ { - structField := t.Field(i) - fieldEntry := v.Field(i) - representation := fmt.Sprintf("%s: %s", structField.Name, formatValue(fieldEntry, indentation+1)) - result = append(result, representation) - if len(representation) > longest { - longest = len(representation) - } - } - if longest > longFormThreshold { - indenter := strings.Repeat(Indent, int(indentation)) - return fmt.Sprintf("{\n%s%s,\n%s}", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) - } else { - return fmt.Sprintf("{%s}", strings.Join(result, ", ")) - } -} - -func isNilValue(a reflect.Value) bool { - switch a.Kind() { - case reflect.Invalid: - return true - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return a.IsNil() - } - - return false -} - -func isNil(a interface{}) bool { - if a == nil { - return true - } - - switch reflect.TypeOf(a).Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return reflect.ValueOf(a).IsNil() - } - - return false -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/format/format_suite_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/format/format_suite_test.go deleted file mode 100644 index 8e65a95..0000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/format/format_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package format_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestFormat(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Format Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/format/format_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/format/format_test.go deleted file mode 100644 index fd926f5..0000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/format/format_test.go +++ /dev/null @@ -1,449 +0,0 @@ -package format_test - -import ( - "fmt" - "strings" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/format" - "github.com/onsi/gomega/types" -) - -//recursive struct - -type StringAlias string -type ByteAlias []byte -type IntAlias int - -type AStruct struct { - Exported string -} - -type SimpleStruct struct { - Name string - Enumeration int - Veritas bool - Data []byte - secret uint32 -} - -type ComplexStruct struct { - Strings []string - SimpleThings []*SimpleStruct - DataMaps map[int]ByteAlias -} - -type SecretiveStruct struct { - boolValue bool - intValue int - uintValue uint - uintptrValue uintptr - floatValue float32 - complexValue complex64 - chanValue chan bool - funcValue func() - pointerValue *int - sliceValue []string - byteSliceValue []byte - stringValue string - arrValue [3]int - byteArrValue [3]byte - mapValue map[string]int - structValue AStruct - interfaceValue interface{} -} - -type GoStringer struct { -} - -func (g GoStringer) GoString() string { - return "go-string" -} - -func (g GoStringer) String() string { - return "string" -} - -type Stringer struct { -} - -func (g Stringer) String() string { - return "string" -} - -var _ = Describe("Format", func() { - match := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher { - if len(args) > 0 { - valueRepresentation = fmt.Sprintf(valueRepresentation, args...) - } - return Equal(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation)) - } - - matchRegexp := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher { - if len(args) > 0 { - valueRepresentation = fmt.Sprintf(valueRepresentation, args...) - } - return MatchRegexp(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation)) - } - - hashMatchingRegexp := func(entries ...string) string { - entriesSwitch := "(" + strings.Join(entries, "|") + ")" - arr := make([]string, len(entries)) - for i := range arr { - arr[i] = entriesSwitch - } - return "{" + strings.Join(arr, ", ") + "}" - } - - Describe("Message", func() { - Context("with only an actual value", func() { - It("should print out an indented formatted representation of the value and the message", func() { - Ω(Message(3, "to be three.")).Should(Equal("Expected\n : 3\nto be three.")) - }) - }) - - Context("with an actual and an expected value", func() { - It("should print out an indented formatted representatino of both values, and the message", func() { - Ω(Message(3, "to equal", 4)).Should(Equal("Expected\n : 3\nto equal\n : 4")) - }) - }) - }) - - Describe("IndentString", func() { - It("should indent the string", func() { - Ω(IndentString("foo\n bar\nbaz", 2)).Should(Equal(" foo\n bar\n baz")) - }) - }) - - Describe("Object", func() { - Describe("formatting boolean values", func() { - It("should give the type and format values correctly", func() { - Ω(Object(true, 1)).Should(match("bool", "true")) - Ω(Object(false, 1)).Should(match("bool", "false")) - }) - }) - - Describe("formatting numbers", func() { - It("should give the type and format values correctly", func() { - Ω(Object(int(3), 1)).Should(match("int", "3")) - Ω(Object(int8(3), 1)).Should(match("int8", "3")) - Ω(Object(int16(3), 1)).Should(match("int16", "3")) - Ω(Object(int32(3), 1)).Should(match("int32", "3")) - Ω(Object(int64(3), 1)).Should(match("int64", "3")) - - Ω(Object(uint(3), 1)).Should(match("uint", "3")) - Ω(Object(uint8(3), 1)).Should(match("uint8", "3")) - Ω(Object(uint16(3), 1)).Should(match("uint16", "3")) - Ω(Object(uint32(3), 1)).Should(match("uint32", "3")) - Ω(Object(uint64(3), 1)).Should(match("uint64", "3")) - }) - - It("should handle uintptr differently", func() { - Ω(Object(uintptr(3), 1)).Should(match("uintptr", "0x3")) - }) - }) - - Describe("formatting channels", func() { - It("should give the type and format values correctly", func() { - c := make(chan<- bool, 3) - c <- true - c <- false - Ω(Object(c, 1)).Should(match("chan<- bool | len:2, cap:3", "%v", c)) - }) - }) - - Describe("formatting strings", func() { - It("should give the type and format values correctly", func() { - s := "a\nb\nc" - Ω(Object(s, 1)).Should(match("string", `a - b - c`)) - }) - }) - - Describe("formatting []byte slices", func() { - It("should present them as strings", func() { - b := []byte("a\nb\nc") - Ω(Object(b, 1)).Should(matchRegexp(`\[\]uint8 \| len:5, cap:\d+`, `a - b - c`)) - }) - }) - - Describe("formatting functions", func() { - It("should give the type and format values correctly", func() { - f := func(a string, b []int) ([]byte, error) { - return []byte("abc"), nil - } - Ω(Object(f, 1)).Should(match("func(string, []int) ([]uint8, error)", "%v", f)) - }) - }) - - Describe("formatting pointers", func() { - It("should give the type and dereference the value to format it correctly", func() { - a := 3 - Ω(Object(&a, 1)).Should(match(fmt.Sprintf("*int | %p", &a), "3")) - }) - - Context("when there are pointers to pointers...", func() { - It("should recursively deference the pointer until it gets to a value", func() { - a := 3 - var b *int - var c **int - var d ***int - b = &a - c = &b - d = &c - - Ω(Object(d, 1)).Should(match(fmt.Sprintf("***int | %p", d), "3")) - }) - }) - - Context("when the pointer points to nil", func() { - It("should say nil and not explode", func() { - var a *AStruct - Ω(Object(a, 1)).Should(match("*format_test.AStruct | 0x0", "nil")) - }) - }) - }) - - Describe("formatting arrays", func() { - It("should give the type and format values correctly", func() { - w := [3]string{"Jed Bartlet", "Toby Ziegler", "CJ Cregg"} - Ω(Object(w, 1)).Should(match("[3]string", `["Jed Bartlet", "Toby Ziegler", "CJ Cregg"]`)) - }) - - Context("with byte arrays", func() { - It("should give the type and format values correctly", func() { - w := [3]byte{17, 28, 19} - Ω(Object(w, 1)).Should(match("[3]uint8", `[17, 28, 19]`)) - }) - }) - }) - - Describe("formatting slices", func() { - It("should include the length and capacity in the type information", func() { - s := make([]bool, 3, 4) - Ω(Object(s, 1)).Should(match("[]bool | len:3, cap:4", "[false, false, false]")) - }) - - Context("when the slice contains long entries", func() { - It("should format the entries with newlines", func() { - w := []string{"Josiah Edward Bartlet", "Toby Ziegler", "CJ Cregg"} - expected := `[ - "Josiah Edward Bartlet", - "Toby Ziegler", - "CJ Cregg", - ]` - Ω(Object(w, 1)).Should(match("[]string | len:3, cap:3", expected)) - }) - }) - }) - - Describe("formatting maps", func() { - It("should include the length in the type information", func() { - m := make(map[int]bool, 5) - m[3] = true - m[4] = false - Ω(Object(m, 1)).Should(matchRegexp(`map\[int\]bool \| len:2`, hashMatchingRegexp("3: true", "4: false"))) - }) - - Context("when the slice contains long entries", func() { - It("should format the entries with newlines", func() { - m := map[string][]byte{} - m["Josiah Edward Bartlet"] = []byte("Martin Sheen") - m["Toby Ziegler"] = []byte("Richard Schiff") - m["CJ Cregg"] = []byte("Allison Janney") - expected := `{ - ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), - ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), - ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), - }` - Ω(Object(m, 1)).Should(matchRegexp(`map\[string\]\[\]uint8 \| len:3`, expected)) - }) - }) - }) - - Describe("formatting structs", func() { - It("should include the struct name and the field names", func() { - s := SimpleStruct{ - Name: "Oswald", - Enumeration: 17, - Veritas: true, - Data: []byte("datum"), - secret: 1983, - } - - Ω(Object(s, 1)).Should(match("format_test.SimpleStruct", `{Name: "Oswald", Enumeration: 17, Veritas: true, Data: "datum", secret: 1983}`)) - }) - - Context("when the struct contains long entries", func() { - It("should format the entries with new lines", func() { - s := &SimpleStruct{ - Name: "Mithrandir Gandalf Greyhame", - Enumeration: 2021, - Veritas: true, - Data: []byte("wizard"), - secret: 3, - } - - Ω(Object(s, 1)).Should(match(fmt.Sprintf("*format_test.SimpleStruct | %p", s), `{ - Name: "Mithrandir Gandalf Greyhame", - Enumeration: 2021, - Veritas: true, - Data: "wizard", - secret: 3, - }`)) - }) - }) - }) - - Describe("formatting nil values", func() { - It("should print out nil", func() { - Ω(Object(nil, 1)).Should(match("nil", "nil")) - var typedNil *AStruct - Ω(Object(typedNil, 1)).Should(match("*format_test.AStruct | 0x0", "nil")) - var c chan<- bool - Ω(Object(c, 1)).Should(match("chan<- bool | len:0, cap:0", "nil")) - var s []string - Ω(Object(s, 1)).Should(match("[]string | len:0, cap:0", "nil")) - var m map[string]bool - Ω(Object(m, 1)).Should(match("map[string]bool | len:0", "nil")) - }) - }) - - Describe("formatting aliased types", func() { - It("should print out the correct alias type", func() { - Ω(Object(StringAlias("alias"), 1)).Should(match("format_test.StringAlias", `alias`)) - Ω(Object(ByteAlias("alias"), 1)).Should(matchRegexp(`format_test\.ByteAlias \| len:5, cap:\d+`, `alias`)) - Ω(Object(IntAlias(3), 1)).Should(match("format_test.IntAlias", "3")) - }) - }) - - Describe("handling nested things", func() { - It("should produce a correctly nested representation", func() { - s := ComplexStruct{ - Strings: []string{"lots", "of", "short", "strings"}, - SimpleThings: []*SimpleStruct{ - {"short", 7, true, []byte("succinct"), 17}, - {"something longer", 427, true, []byte("designed to wrap around nicely"), 30}, - }, - DataMaps: map[int]ByteAlias{ - 17: ByteAlias("some substantially longer chunks of data"), - 1138: ByteAlias("that should make things wrap"), - }, - } - expected := `{ - Strings: \["lots", "of", "short", "strings"\], - SimpleThings: \[ - {Name: "short", Enumeration: 7, Veritas: true, Data: "succinct", secret: 17}, - { - Name: "something longer", - Enumeration: 427, - Veritas: true, - Data: "designed to wrap around nicely", - secret: 30, - }, - \], - DataMaps: { - (17: "some substantially longer chunks of data"|1138: "that should make things wrap"), - (17: "some substantially longer chunks of data"|1138: "that should make things wrap"), - }, - }` - Ω(Object(s, 1)).Should(matchRegexp(`format_test\.ComplexStruct`, expected)) - }) - }) - }) - - Describe("Handling unexported fields in structs", func() { - It("should handle all the various types correctly", func() { - a := int(5) - s := SecretiveStruct{ - boolValue: true, - intValue: 3, - uintValue: 4, - uintptrValue: 5, - floatValue: 6.0, - complexValue: complex(5.0, 3.0), - chanValue: make(chan bool, 2), - funcValue: func() {}, - pointerValue: &a, - sliceValue: []string{"string", "slice"}, - byteSliceValue: []byte("bytes"), - stringValue: "a string", - arrValue: [3]int{11, 12, 13}, - byteArrValue: [3]byte{17, 20, 32}, - mapValue: map[string]int{"a key": 20, "b key": 30}, - structValue: AStruct{"exported"}, - interfaceValue: map[string]int{"a key": 17}, - } - - expected := fmt.Sprintf(`{ - boolValue: true, - intValue: 3, - uintValue: 4, - uintptrValue: 0x5, - floatValue: 6, - complexValue: \(5\+3i\), - chanValue: %p, - funcValue: %p, - pointerValue: 5, - sliceValue: \["string", "slice"\], - byteSliceValue: "bytes", - stringValue: "a string", - arrValue: \[11, 12, 13\], - byteArrValue: \[17, 20, 32\], - mapValue: %s, - structValue: {Exported: "exported"}, - interfaceValue: {"a key": 17}, - }`, s.chanValue, s.funcValue, hashMatchingRegexp(`"a key": 20`, `"b key": 30`)) - - Ω(Object(s, 1)).Should(matchRegexp(`format_test\.SecretiveStruct`, expected)) - }) - }) - - Describe("Handling interfaces", func() { - It("should unpack the interface", func() { - outerHash := map[string]interface{}{} - innerHash := map[string]int{} - - innerHash["inner"] = 3 - outerHash["integer"] = 2 - outerHash["map"] = innerHash - - expected := hashMatchingRegexp(`"integer": 2`, `"map": {"inner": 3}`) - Ω(Object(outerHash, 1)).Should(matchRegexp(`map\[string\]interface {} \| len:2`, expected)) - }) - }) - - Describe("Handling recursive things", func() { - It("should not go crazy...", func() { - m := map[string]interface{}{} - m["integer"] = 2 - m["map"] = m - Ω(Object(m, 1)).Should(ContainSubstring("...")) - }) - }) - - Describe("When instructed to use the Stringer representation", func() { - BeforeEach(func() { - UseStringerRepresentation = true - }) - - AfterEach(func() { - UseStringerRepresentation = false - }) - - Context("when passed a GoStringer", func() { - It("should use what GoString() returns", func() { - Ω(Object(GoStringer{}, 1)).Should(ContainSubstring(": go-string")) - }) - }) - - Context("when passed a stringer", func() { - It("should use what String() returns", func() { - Ω(Object(Stringer{}, 1)).Should(ContainSubstring(": string")) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/buffer.go b/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/buffer.go deleted file mode 100644 index 8775b86..0000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/buffer.go +++ /dev/null @@ -1,229 +0,0 @@ -/* -Package gbytes provides a buffer that supports incrementally detecting input. - -You use gbytes.Buffer with the gbytes.Say matcher. When Say finds a match, it fastforwards the buffer's read cursor to the end of that match. - -Subsequent matches against the buffer will only operate against data that appears *after* the read cursor. - -The read cursor is an opaque implementation detail that you cannot access. You should use the Say matcher to sift through the buffer. You can always -access the entire buffer's contents with Contents(). - -*/ -package gbytes - -import ( - "errors" - "fmt" - "io" - "regexp" - "sync" - "time" -) - -/* -gbytes.Buffer implements an io.Writer and can be used with the gbytes.Say matcher. - -You should only use a gbytes.Buffer in test code. It stores all writes in an in-memory buffer - behavior that is inappropriate for production code! -*/ -type Buffer struct { - contents []byte - readCursor uint64 - lock *sync.Mutex - detectCloser chan interface{} - closed bool -} - -/* -NewBuffer returns a new gbytes.Buffer -*/ -func NewBuffer() *Buffer { - return &Buffer{ - lock: &sync.Mutex{}, - } -} - -/* -BufferWithBytes returns a new gbytes.Buffer seeded with the passed in bytes -*/ -func BufferWithBytes(bytes []byte) *Buffer { - return &Buffer{ - lock: &sync.Mutex{}, - contents: bytes, - } -} - -/* -Write implements the io.Writer interface -*/ -func (b *Buffer) Write(p []byte) (n int, err error) { - b.lock.Lock() - defer b.lock.Unlock() - - if b.closed { - return 0, errors.New("attempt to write to closed buffer") - } - - b.contents = append(b.contents, p...) - return len(p), nil -} - -/* -Read implements the io.Reader interface. It advances the -cursor as it reads. - -Returns an error if called after Close. -*/ -func (b *Buffer) Read(d []byte) (int, error) { - b.lock.Lock() - defer b.lock.Unlock() - - if b.closed { - return 0, errors.New("attempt to read from closed buffer") - } - - if uint64(len(b.contents)) <= b.readCursor { - return 0, io.EOF - } - - n := copy(d, b.contents[b.readCursor:]) - b.readCursor += uint64(n) - - return n, nil -} - -/* -Close signifies that the buffer will no longer be written to -*/ -func (b *Buffer) Close() error { - b.lock.Lock() - defer b.lock.Unlock() - - b.closed = true - - return nil -} - -/* -Closed returns true if the buffer has been closed -*/ -func (b *Buffer) Closed() bool { - b.lock.Lock() - defer b.lock.Unlock() - - return b.closed -} - -/* -Contents returns all data ever written to the buffer. -*/ -func (b *Buffer) Contents() []byte { - b.lock.Lock() - defer b.lock.Unlock() - - contents := make([]byte, len(b.contents)) - copy(contents, b.contents) - return contents -} - -/* -Detect takes a regular expression and returns a channel. - -The channel will receive true the first time data matching the regular expression is written to the buffer. -The channel is subsequently closed and the buffer's read-cursor is fast-forwarded to just after the matching region. - -You typically don't need to use Detect and should use the ghttp.Say matcher instead. Detect is useful, however, in cases where your code must -be branch and handle different outputs written to the buffer. - -For example, consider a buffer hooked up to the stdout of a client library. You may (or may not, depending on state outside of your control) need to authenticate the client library. - -You could do something like: - -select { -case <-buffer.Detect("You are not logged in"): - //log in -case <-buffer.Detect("Success"): - //carry on -case <-time.After(time.Second): - //welp -} -buffer.CancelDetects() - -You should always call CancelDetects after using Detect. This will close any channels that have not detected and clean up the goroutines that were spawned to support them. - -Finally, you can pass detect a format string followed by variadic arguments. This will construct the regexp using fmt.Sprintf. -*/ -func (b *Buffer) Detect(desired string, args ...interface{}) chan bool { - formattedRegexp := desired - if len(args) > 0 { - formattedRegexp = fmt.Sprintf(desired, args...) - } - re := regexp.MustCompile(formattedRegexp) - - b.lock.Lock() - defer b.lock.Unlock() - - if b.detectCloser == nil { - b.detectCloser = make(chan interface{}) - } - - closer := b.detectCloser - response := make(chan bool) - go func() { - ticker := time.NewTicker(10 * time.Millisecond) - defer ticker.Stop() - defer close(response) - for { - select { - case <-ticker.C: - b.lock.Lock() - data, cursor := b.contents[b.readCursor:], b.readCursor - loc := re.FindIndex(data) - b.lock.Unlock() - - if loc != nil { - response <- true - b.lock.Lock() - newCursorPosition := cursor + uint64(loc[1]) - if newCursorPosition >= b.readCursor { - b.readCursor = newCursorPosition - } - b.lock.Unlock() - return - } - case <-closer: - return - } - } - }() - - return response -} - -/* -CancelDetects cancels any pending detects and cleans up their goroutines. You should always call this when you're done with a set of Detect channels. -*/ -func (b *Buffer) CancelDetects() { - b.lock.Lock() - defer b.lock.Unlock() - - close(b.detectCloser) - b.detectCloser = nil -} - -func (b *Buffer) didSay(re *regexp.Regexp) (bool, []byte) { - b.lock.Lock() - defer b.lock.Unlock() - - unreadBytes := b.contents[b.readCursor:] - copyOfUnreadBytes := make([]byte, len(unreadBytes)) - copy(copyOfUnreadBytes, unreadBytes) - - loc := re.FindIndex(unreadBytes) - - if loc != nil { - b.readCursor += uint64(loc[1]) - return true, copyOfUnreadBytes - } else { - return false, copyOfUnreadBytes - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/buffer_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/buffer_test.go deleted file mode 100644 index b111138..0000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/buffer_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package gbytes_test - -import ( - "io" - "time" - - . "github.com/onsi/gomega/gbytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Buffer", func() { - var buffer *Buffer - - BeforeEach(func() { - buffer = NewBuffer() - }) - - Describe("dumping the entire contents of the buffer", func() { - It("should return everything that's been written", func() { - buffer.Write([]byte("abc")) - buffer.Write([]byte("def")) - Ω(buffer.Contents()).Should(Equal([]byte("abcdef"))) - - Ω(buffer).Should(Say("bcd")) - Ω(buffer.Contents()).Should(Equal([]byte("abcdef"))) - }) - }) - - Describe("creating a buffer with bytes", func() { - It("should create the buffer with the cursor set to the beginning", func() { - buffer := BufferWithBytes([]byte("abcdef")) - Ω(buffer.Contents()).Should(Equal([]byte("abcdef"))) - Ω(buffer).Should(Say("abc")) - Ω(buffer).ShouldNot(Say("abc")) - Ω(buffer).Should(Say("def")) - }) - }) - - Describe("reading from a buffer", func() { - It("should read the current contents of the buffer", func() { - buffer := BufferWithBytes([]byte("abcde")) - - dest := make([]byte, 3) - n, err := buffer.Read(dest) - Ω(err).ShouldNot(HaveOccurred()) - Ω(n).Should(Equal(3)) - Ω(string(dest)).Should(Equal("abc")) - - dest = make([]byte, 3) - n, err = buffer.Read(dest) - Ω(err).ShouldNot(HaveOccurred()) - Ω(n).Should(Equal(2)) - Ω(string(dest[:n])).Should(Equal("de")) - - n, err = buffer.Read(dest) - Ω(err).Should(Equal(io.EOF)) - Ω(n).Should(Equal(0)) - }) - - Context("after the buffer has been closed", func() { - It("returns an error", func() { - buffer := BufferWithBytes([]byte("abcde")) - - buffer.Close() - - dest := make([]byte, 3) - n, err := buffer.Read(dest) - Ω(err).Should(HaveOccurred()) - Ω(n).Should(Equal(0)) - }) - }) - }) - - Describe("detecting regular expressions", func() { - It("should fire the appropriate channel when the passed in pattern matches, then close it", func(done Done) { - go func() { - time.Sleep(10 * time.Millisecond) - buffer.Write([]byte("abcde")) - }() - - A := buffer.Detect("%s", "a.c") - B := buffer.Detect("def") - - var gotIt bool - select { - case gotIt = <-A: - case <-B: - Fail("should not have gotten here") - } - - Ω(gotIt).Should(BeTrue()) - Eventually(A).Should(BeClosed()) - - buffer.Write([]byte("f")) - Eventually(B).Should(Receive()) - Eventually(B).Should(BeClosed()) - - close(done) - }) - - It("should fast-forward the buffer upon detection", func(done Done) { - buffer.Write([]byte("abcde")) - <-buffer.Detect("abc") - Ω(buffer).ShouldNot(Say("abc")) - Ω(buffer).Should(Say("de")) - close(done) - }) - - It("should only fast-forward the buffer when the channel is read, and only if doing so would not rewind it", func(done Done) { - buffer.Write([]byte("abcde")) - A := buffer.Detect("abc") - time.Sleep(20 * time.Millisecond) //give the goroutine a chance to detect and write to the channel - Ω(buffer).Should(Say("abcd")) - <-A - Ω(buffer).ShouldNot(Say("d")) - Ω(buffer).Should(Say("e")) - Eventually(A).Should(BeClosed()) - close(done) - }) - - It("should be possible to cancel a detection", func(done Done) { - A := buffer.Detect("abc") - B := buffer.Detect("def") - buffer.CancelDetects() - buffer.Write([]byte("abcdef")) - Eventually(A).Should(BeClosed()) - Eventually(B).Should(BeClosed()) - - Ω(buffer).Should(Say("bcde")) - <-buffer.Detect("f") - close(done) - }) - }) - - Describe("closing the buffer", func() { - It("should error when further write attempts are made", func() { - _, err := buffer.Write([]byte("abc")) - Ω(err).ShouldNot(HaveOccurred()) - - buffer.Close() - - _, err = buffer.Write([]byte("def")) - Ω(err).Should(HaveOccurred()) - - Ω(buffer.Contents()).Should(Equal([]byte("abc"))) - }) - - It("should be closed", func() { - Ω(buffer.Closed()).Should(BeFalse()) - - buffer.Close() - - Ω(buffer.Closed()).Should(BeTrue()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/gbuffer_suite_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/gbuffer_suite_test.go deleted file mode 100644 index 3a7dc06..0000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/gbuffer_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package gbytes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestGbytes(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Gbytes Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/say_matcher.go b/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/say_matcher.go deleted file mode 100644 index ce5ebcb..0000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/say_matcher.go +++ /dev/null @@ -1,105 +0,0 @@ -package gbytes - -import ( - "fmt" - "regexp" - - "github.com/onsi/gomega/format" -) - -//Objects satisfying the BufferProvider can be used with the Say matcher. -type BufferProvider interface { - Buffer() *Buffer -} - -/* -Say is a Gomega matcher that operates on gbytes.Buffers: - - Ω(buffer).Should(Say("something")) - -will succeed if the unread portion of the buffer matches the regular expression "something". - -When Say succeeds, it fast forwards the gbytes.Buffer's read cursor to just after the succesful match. -Thus, subsequent calls to Say will only match against the unread portion of the buffer - -Say pairs very well with Eventually. To asser that a buffer eventually receives data matching "[123]-star" within 3 seconds you can: - - Eventually(buffer, 3).Should(Say("[123]-star")) - -Ditto with consistently. To assert that a buffer does not receive data matching "never-see-this" for 1 second you can: - - Consistently(buffer, 1).ShouldNot(Say("never-see-this")) - -In addition to bytes.Buffers, Say can operate on objects that implement the gbytes.BufferProvider interface. -In such cases, Say simply operates on the *gbytes.Buffer returned by Buffer() - -If the buffer is closed, the Say matcher will tell Eventually to abort. -*/ -func Say(expected string, args ...interface{}) *sayMatcher { - formattedRegexp := expected - if len(args) > 0 { - formattedRegexp = fmt.Sprintf(expected, args...) - } - return &sayMatcher{ - re: regexp.MustCompile(formattedRegexp), - } -} - -type sayMatcher struct { - re *regexp.Regexp - receivedSayings []byte -} - -func (m *sayMatcher) buffer(actual interface{}) (*Buffer, bool) { - var buffer *Buffer - - switch x := actual.(type) { - case *Buffer: - buffer = x - case BufferProvider: - buffer = x.Buffer() - default: - return nil, false - } - - return buffer, true -} - -func (m *sayMatcher) Match(actual interface{}) (success bool, err error) { - buffer, ok := m.buffer(actual) - if !ok { - return false, fmt.Errorf("Say must be passed a *gbytes.Buffer or BufferProvider. Got:\n%s", format.Object(actual, 1)) - } - - didSay, sayings := buffer.didSay(m.re) - m.receivedSayings = sayings - - return didSay, nil -} - -func (m *sayMatcher) FailureMessage(actual interface{}) (message string) { - return fmt.Sprintf( - "Got stuck at:\n%s\nWaiting for:\n%s", - format.IndentString(string(m.receivedSayings), 1), - format.IndentString(m.re.String(), 1), - ) -} - -func (m *sayMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return fmt.Sprintf( - "Saw:\n%s\nWhich matches the unexpected:\n%s", - format.IndentString(string(m.receivedSayings), 1), - format.IndentString(m.re.String(), 1), - ) -} - -func (m *sayMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { - switch x := actual.(type) { - case *Buffer: - return !x.Closed() - case BufferProvider: - return !x.Buffer().Closed() - default: - return true - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/say_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/say_matcher_test.go deleted file mode 100644 index d0ddf1f..0000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/say_matcher_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package gbytes_test - -import ( - "time" - . "github.com/onsi/gomega/gbytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type speaker struct { - buffer *Buffer -} - -func (s *speaker) Buffer() *Buffer { - return s.buffer -} - -var _ = Describe("SayMatcher", func() { - var buffer *Buffer - - BeforeEach(func() { - buffer = NewBuffer() - buffer.Write([]byte("abc")) - }) - - Context("when actual is not a gexec Buffer, or a BufferProvider", func() { - It("should error", func() { - failures := InterceptGomegaFailures(func() { - Ω("foo").Should(Say("foo")) - }) - Ω(failures[0]).Should(ContainSubstring("*gbytes.Buffer")) - }) - }) - - Context("when a match is found", func() { - It("should succeed", func() { - Ω(buffer).Should(Say("abc")) - }) - - It("should support printf-like formatting", func() { - Ω(buffer).Should(Say("a%sc", "b")) - }) - - It("should use a regular expression", func() { - Ω(buffer).Should(Say("a.c")) - }) - - It("should fastforward the buffer", func() { - buffer.Write([]byte("def")) - Ω(buffer).Should(Say("abcd")) - Ω(buffer).Should(Say("ef")) - Ω(buffer).ShouldNot(Say("[a-z]")) - }) - }) - - Context("when no match is found", func() { - It("should not error", func() { - Ω(buffer).ShouldNot(Say("def")) - }) - - Context("when the buffer is closed", func() { - BeforeEach(func() { - buffer.Close() - }) - - It("should abort an eventually", func() { - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(buffer).Should(Say("def")) - }) - Eventually(buffer).ShouldNot(Say("def")) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - Ω(failures).Should(HaveLen(1)) - - t = time.Now() - Eventually(buffer).Should(Say("abc")) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - }) - - It("should abort a consistently", func() { - t := time.Now() - Consistently(buffer, 2.0).ShouldNot(Say("def")) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - }) - - It("should not error with a synchronous matcher", func() { - Ω(buffer).ShouldNot(Say("def")) - Ω(buffer).Should(Say("abc")) - }) - }) - }) - - Context("when a positive match fails", func() { - It("should report where it got stuck", func() { - Ω(buffer).Should(Say("abc")) - buffer.Write([]byte("def")) - failures := InterceptGomegaFailures(func() { - Ω(buffer).Should(Say("abc")) - }) - Ω(failures[0]).Should(ContainSubstring("Got stuck at:")) - Ω(failures[0]).Should(ContainSubstring("def")) - }) - }) - - Context("when a negative match fails", func() { - It("should report where it got stuck", func() { - failures := InterceptGomegaFailures(func() { - Ω(buffer).ShouldNot(Say("abc")) - }) - Ω(failures[0]).Should(ContainSubstring("Saw:")) - Ω(failures[0]).Should(ContainSubstring("Which matches the unexpected:")) - Ω(failures[0]).Should(ContainSubstring("abc")) - }) - }) - - Context("when a match is not found", func() { - It("should not fastforward the buffer", func() { - Ω(buffer).ShouldNot(Say("def")) - Ω(buffer).Should(Say("abc")) - }) - }) - - Context("a nice real-life example", func() { - It("should behave well", func() { - Ω(buffer).Should(Say("abc")) - go func() { - time.Sleep(10 * time.Millisecond) - buffer.Write([]byte("def")) - }() - Ω(buffer).ShouldNot(Say("def")) - Eventually(buffer).Should(Say("def")) - }) - }) - - Context("when actual is a BufferProvider", func() { - It("should use actual's buffer", func() { - s := &speaker{ - buffer: NewBuffer(), - } - - Ω(s).ShouldNot(Say("abc")) - - s.Buffer().Write([]byte("abc")) - Ω(s).Should(Say("abc")) - }) - - It("should abort an eventually", func() { - s := &speaker{ - buffer: NewBuffer(), - } - - s.buffer.Close() - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(s).Should(Say("def")) - }) - Ω(failures).Should(HaveLen(1)) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - }) - }) -}) diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/asm.s b/Godeps/_workspace/src/golang.org/x/sys/windows/asm.s deleted file mode 100644 index d4ca868..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/asm.s +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "textflag.h" - -TEXT ·use(SB),NOSPLIT,$0 - RET diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/asm_windows_386.s b/Godeps/_workspace/src/golang.org/x/sys/windows/asm_windows_386.s deleted file mode 100644 index 1c20dd2..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/asm_windows_386.s +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// -// System calls for 386, Windows are implemented in runtime/syscall_windows.goc -// - -TEXT ·getprocaddress(SB), 7, $0-8 - JMP syscall·getprocaddress(SB) - -TEXT ·loadlibrary(SB), 7, $0-4 - JMP syscall·loadlibrary(SB) diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/asm_windows_amd64.s b/Godeps/_workspace/src/golang.org/x/sys/windows/asm_windows_amd64.s deleted file mode 100644 index 4d025ab..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/asm_windows_amd64.s +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// -// System calls for amd64, Windows are implemented in runtime/syscall_windows.goc -// - -TEXT ·getprocaddress(SB), 7, $0-32 - JMP syscall·getprocaddress(SB) - -TEXT ·loadlibrary(SB), 7, $0-8 - JMP syscall·loadlibrary(SB) diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/dll_windows.go b/Godeps/_workspace/src/golang.org/x/sys/windows/dll_windows.go deleted file mode 100644 index 7f9f05f..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/dll_windows.go +++ /dev/null @@ -1,275 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package windows - -import ( - "sync" - "sync/atomic" - "syscall" - "unsafe" -) - -// DLLError describes reasons for DLL load failures. -type DLLError struct { - Err error - ObjName string - Msg string -} - -func (e *DLLError) Error() string { return e.Msg } - -// Implemented in runtime/syscall_windows.goc; we provide jumps to them in our assembly file. -func loadlibrary(filename *uint16) (handle uintptr, err syscall.Errno) -func getprocaddress(handle uintptr, procname *uint8) (proc uintptr, err syscall.Errno) - -// A DLL implements access to a single DLL. -type DLL struct { - Name string - Handle Handle -} - -// LoadDLL loads DLL file into memory. -func LoadDLL(name string) (dll *DLL, err error) { - namep, err := UTF16PtrFromString(name) - if err != nil { - return nil, err - } - h, e := loadlibrary(namep) - if e != 0 { - return nil, &DLLError{ - Err: e, - ObjName: name, - Msg: "Failed to load " + name + ": " + e.Error(), - } - } - d := &DLL{ - Name: name, - Handle: Handle(h), - } - return d, nil -} - -// MustLoadDLL is like LoadDLL but panics if load operation failes. -func MustLoadDLL(name string) *DLL { - d, e := LoadDLL(name) - if e != nil { - panic(e) - } - return d -} - -// FindProc searches DLL d for procedure named name and returns *Proc -// if found. It returns an error if search fails. -func (d *DLL) FindProc(name string) (proc *Proc, err error) { - namep, err := BytePtrFromString(name) - if err != nil { - return nil, err - } - a, e := getprocaddress(uintptr(d.Handle), namep) - if e != 0 { - return nil, &DLLError{ - Err: e, - ObjName: name, - Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(), - } - } - p := &Proc{ - Dll: d, - Name: name, - addr: a, - } - return p, nil -} - -// MustFindProc is like FindProc but panics if search fails. -func (d *DLL) MustFindProc(name string) *Proc { - p, e := d.FindProc(name) - if e != nil { - panic(e) - } - return p -} - -// Release unloads DLL d from memory. -func (d *DLL) Release() (err error) { - return FreeLibrary(d.Handle) -} - -// A Proc implements access to a procedure inside a DLL. -type Proc struct { - Dll *DLL - Name string - addr uintptr -} - -// Addr returns the address of the procedure represented by p. -// The return value can be passed to Syscall to run the procedure. -func (p *Proc) Addr() uintptr { - return p.addr -} - -// Call executes procedure p with arguments a. It will panic, if more then 15 arguments -// are supplied. -// -// The returned error is always non-nil, constructed from the result of GetLastError. -// Callers must inspect the primary return value to decide whether an error occurred -// (according to the semantics of the specific function being called) before consulting -// the error. The error will be guaranteed to contain windows.Errno. -func (p *Proc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) { - switch len(a) { - case 0: - return syscall.Syscall(p.Addr(), uintptr(len(a)), 0, 0, 0) - case 1: - return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], 0, 0) - case 2: - return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], a[1], 0) - case 3: - return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], a[1], a[2]) - case 4: - return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], 0, 0) - case 5: - return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], 0) - case 6: - return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5]) - case 7: - return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], 0, 0) - case 8: - return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], 0) - case 9: - return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]) - case 10: - return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], 0, 0) - case 11: - return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], 0) - case 12: - return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11]) - case 13: - return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], 0, 0) - case 14: - return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], 0) - case 15: - return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14]) - default: - panic("Call " + p.Name + " with too many arguments " + itoa(len(a)) + ".") - } - return -} - -// A LazyDLL implements access to a single DLL. -// It will delay the load of the DLL until the first -// call to its Handle method or to one of its -// LazyProc's Addr method. -type LazyDLL struct { - mu sync.Mutex - dll *DLL // non nil once DLL is loaded - Name string -} - -// Load loads DLL file d.Name into memory. It returns an error if fails. -// Load will not try to load DLL, if it is already loaded into memory. -func (d *LazyDLL) Load() error { - // Non-racy version of: - // if d.dll == nil { - if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll))) == nil { - d.mu.Lock() - defer d.mu.Unlock() - if d.dll == nil { - dll, e := LoadDLL(d.Name) - if e != nil { - return e - } - // Non-racy version of: - // d.dll = dll - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll)), unsafe.Pointer(dll)) - } - } - return nil -} - -// mustLoad is like Load but panics if search fails. -func (d *LazyDLL) mustLoad() { - e := d.Load() - if e != nil { - panic(e) - } -} - -// Handle returns d's module handle. -func (d *LazyDLL) Handle() uintptr { - d.mustLoad() - return uintptr(d.dll.Handle) -} - -// NewProc returns a LazyProc for accessing the named procedure in the DLL d. -func (d *LazyDLL) NewProc(name string) *LazyProc { - return &LazyProc{l: d, Name: name} -} - -// NewLazyDLL creates new LazyDLL associated with DLL file. -func NewLazyDLL(name string) *LazyDLL { - return &LazyDLL{Name: name} -} - -// A LazyProc implements access to a procedure inside a LazyDLL. -// It delays the lookup until the Addr method is called. -type LazyProc struct { - mu sync.Mutex - Name string - l *LazyDLL - proc *Proc -} - -// Find searches DLL for procedure named p.Name. It returns -// an error if search fails. Find will not search procedure, -// if it is already found and loaded into memory. -func (p *LazyProc) Find() error { - // Non-racy version of: - // if p.proc == nil { - if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc))) == nil { - p.mu.Lock() - defer p.mu.Unlock() - if p.proc == nil { - e := p.l.Load() - if e != nil { - return e - } - proc, e := p.l.dll.FindProc(p.Name) - if e != nil { - return e - } - // Non-racy version of: - // p.proc = proc - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc)), unsafe.Pointer(proc)) - } - } - return nil -} - -// mustFind is like Find but panics if search fails. -func (p *LazyProc) mustFind() { - e := p.Find() - if e != nil { - panic(e) - } -} - -// Addr returns the address of the procedure represented by p. -// The return value can be passed to Syscall to run the procedure. -func (p *LazyProc) Addr() uintptr { - p.mustFind() - return p.proc.Addr() -} - -// Call executes procedure p with arguments a. It will panic, if more then 15 arguments -// are supplied. -// -// The returned error is always non-nil, constructed from the result of GetLastError. -// Callers must inspect the primary return value to decide whether an error occurred -// (according to the semantics of the specific function being called) before consulting -// the error. The error will be guaranteed to contain windows.Errno. -func (p *LazyProc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) { - p.mustFind() - return p.proc.Call(a...) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/env_unset.go b/Godeps/_workspace/src/golang.org/x/sys/windows/env_unset.go deleted file mode 100644 index 999ffac..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/env_unset.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.4 - -package windows - -import "syscall" - -func Unsetenv(key string) error { - // This was added in Go 1.4. - return syscall.Unsetenv(key) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/env_windows.go b/Godeps/_workspace/src/golang.org/x/sys/windows/env_windows.go deleted file mode 100644 index a9d8ef4..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/env_windows.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Windows environment variables. - -package windows - -import "syscall" - -func Getenv(key string) (value string, found bool) { - return syscall.Getenv(key) -} - -func Setenv(key, value string) error { - return syscall.Setenv(key, value) -} - -func Clearenv() { - syscall.Clearenv() -} - -func Environ() []string { - return syscall.Environ() -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/eventlog.go b/Godeps/_workspace/src/golang.org/x/sys/windows/eventlog.go deleted file mode 100644 index 40af946..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/eventlog.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package windows - -const ( - EVENTLOG_SUCCESS = 0 - EVENTLOG_ERROR_TYPE = 1 - EVENTLOG_WARNING_TYPE = 2 - EVENTLOG_INFORMATION_TYPE = 4 - EVENTLOG_AUDIT_SUCCESS = 8 - EVENTLOG_AUDIT_FAILURE = 16 -) - -//sys RegisterEventSource(uncServerName *uint16, sourceName *uint16) (handle Handle, err error) [failretval==0] = advapi32.RegisterEventSourceW -//sys DeregisterEventSource(handle Handle) (err error) = advapi32.DeregisterEventSource -//sys ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrSId uintptr, numStrings uint16, dataSize uint32, strings **uint16, rawData *byte) (err error) = advapi32.ReportEventW diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/exec_windows.go b/Godeps/_workspace/src/golang.org/x/sys/windows/exec_windows.go deleted file mode 100644 index 3606c3a..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/exec_windows.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Fork, exec, wait, etc. - -package windows - -// EscapeArg rewrites command line argument s as prescribed -// in http://msdn.microsoft.com/en-us/library/ms880421. -// This function returns "" (2 double quotes) if s is empty. -// Alternatively, these transformations are done: -// - every back slash (\) is doubled, but only if immediately -// followed by double quote ("); -// - every double quote (") is escaped by back slash (\); -// - finally, s is wrapped with double quotes (arg -> "arg"), -// but only if there is space or tab inside s. -func EscapeArg(s string) string { - if len(s) == 0 { - return "\"\"" - } - n := len(s) - hasSpace := false - for i := 0; i < len(s); i++ { - switch s[i] { - case '"', '\\': - n++ - case ' ', '\t': - hasSpace = true - } - } - if hasSpace { - n += 2 - } - if n == len(s) { - return s - } - - qs := make([]byte, n) - j := 0 - if hasSpace { - qs[j] = '"' - j++ - } - slashes := 0 - for i := 0; i < len(s); i++ { - switch s[i] { - default: - slashes = 0 - qs[j] = s[i] - case '\\': - slashes++ - qs[j] = s[i] - case '"': - for ; slashes > 0; slashes-- { - qs[j] = '\\' - j++ - } - qs[j] = '\\' - j++ - qs[j] = s[i] - } - j++ - } - if hasSpace { - for ; slashes > 0; slashes-- { - qs[j] = '\\' - j++ - } - qs[j] = '"' - j++ - } - return string(qs[:j]) -} - -func CloseOnExec(fd Handle) { - SetHandleInformation(Handle(fd), HANDLE_FLAG_INHERIT, 0) -} - -// FullPath retrieves the full path of the specified file. -func FullPath(name string) (path string, err error) { - p, err := UTF16PtrFromString(name) - if err != nil { - return "", err - } - n := uint32(100) - for { - buf := make([]uint16, n) - n, err = GetFullPathName(p, uint32(len(buf)), &buf[0], nil) - if err != nil { - return "", err - } - if n <= uint32(len(buf)) { - return UTF16ToString(buf[:n]), nil - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/race.go b/Godeps/_workspace/src/golang.org/x/sys/windows/race.go deleted file mode 100644 index 343e18a..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/race.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows,race - -package windows - -import ( - "runtime" - "unsafe" -) - -const raceenabled = true - -func raceAcquire(addr unsafe.Pointer) { - runtime.RaceAcquire(addr) -} - -func raceReleaseMerge(addr unsafe.Pointer) { - runtime.RaceReleaseMerge(addr) -} - -func raceReadRange(addr unsafe.Pointer, len int) { - runtime.RaceReadRange(addr, len) -} - -func raceWriteRange(addr unsafe.Pointer, len int) { - runtime.RaceWriteRange(addr, len) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/race0.go b/Godeps/_workspace/src/golang.org/x/sys/windows/race0.go deleted file mode 100644 index 17af843..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/race0.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows,!race - -package windows - -import ( - "unsafe" -) - -const raceenabled = false - -func raceAcquire(addr unsafe.Pointer) { -} - -func raceReleaseMerge(addr unsafe.Pointer) { -} - -func raceReadRange(addr unsafe.Pointer, len int) { -} - -func raceWriteRange(addr unsafe.Pointer, len int) { -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/registry/export_test.go b/Godeps/_workspace/src/golang.org/x/sys/windows/registry/export_test.go deleted file mode 100644 index 8badf6f..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/registry/export_test.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package registry - -func (k Key) SetValue(name string, valtype uint32, data []byte) error { - return k.setValue(name, valtype, data) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/registry/key.go b/Godeps/_workspace/src/golang.org/x/sys/windows/registry/key.go deleted file mode 100644 index f087ce5..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/registry/key.go +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -// Package registry provides access to the Windows registry. -// -// Here is a simple example, opening a registry key and reading a string value from it. -// -// k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE) -// if err != nil { -// log.Fatal(err) -// } -// defer k.Close() -// -// s, _, err := k.GetStringValue("SystemRoot") -// if err != nil { -// log.Fatal(err) -// } -// fmt.Printf("Windows system root is %q\n", s) -// -package registry - -import ( - "io" - "syscall" - "time" -) - -const ( - // Registry key security and access rights. - // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724878.aspx - // for details. - ALL_ACCESS = 0xf003f - CREATE_LINK = 0x00020 - CREATE_SUB_KEY = 0x00004 - ENUMERATE_SUB_KEYS = 0x00008 - EXECUTE = 0x20019 - NOTIFY = 0x00010 - QUERY_VALUE = 0x00001 - READ = 0x20019 - SET_VALUE = 0x00002 - WOW64_32KEY = 0x00200 - WOW64_64KEY = 0x00100 - WRITE = 0x20006 -) - -// Key is a handle to an open Windows registry key. -// Keys can be obtained by calling OpenKey; there are -// also some predefined root keys such as CURRENT_USER. -// Keys can be used directly in the Windows API. -type Key syscall.Handle - -const ( - // Windows defines some predefined root keys that are always open. - // An application can use these keys as entry points to the registry. - // Normally these keys are used in OpenKey to open new keys, - // but they can also be used anywhere a Key is required. - CLASSES_ROOT = Key(syscall.HKEY_CLASSES_ROOT) - CURRENT_USER = Key(syscall.HKEY_CURRENT_USER) - LOCAL_MACHINE = Key(syscall.HKEY_LOCAL_MACHINE) - USERS = Key(syscall.HKEY_USERS) - CURRENT_CONFIG = Key(syscall.HKEY_CURRENT_CONFIG) -) - -// Close closes open key k. -func (k Key) Close() error { - return syscall.RegCloseKey(syscall.Handle(k)) -} - -// OpenKey opens a new key with path name relative to key k. -// It accepts any open key, including CURRENT_USER and others, -// and returns the new key and an error. -// The access parameter specifies desired access rights to the -// key to be opened. -func OpenKey(k Key, path string, access uint32) (Key, error) { - p, err := syscall.UTF16PtrFromString(path) - if err != nil { - return 0, err - } - var subkey syscall.Handle - err = syscall.RegOpenKeyEx(syscall.Handle(k), p, 0, access, &subkey) - if err != nil { - return 0, err - } - return Key(subkey), nil -} - -// ReadSubKeyNames returns the names of subkeys of key k. -// The parameter n controls the number of returned names, -// analogous to the way os.File.Readdirnames works. -func (k Key) ReadSubKeyNames(n int) ([]string, error) { - ki, err := k.Stat() - if err != nil { - return nil, err - } - names := make([]string, 0, ki.SubKeyCount) - buf := make([]uint16, ki.MaxSubKeyLen+1) // extra room for terminating zero byte -loopItems: - for i := uint32(0); ; i++ { - if n > 0 { - if len(names) == n { - return names, nil - } - } - l := uint32(len(buf)) - for { - err := syscall.RegEnumKeyEx(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil) - if err == nil { - break - } - if err == syscall.ERROR_MORE_DATA { - // Double buffer size and try again. - l = uint32(2 * len(buf)) - buf = make([]uint16, l) - continue - } - if err == _ERROR_NO_MORE_ITEMS { - break loopItems - } - return names, err - } - names = append(names, syscall.UTF16ToString(buf[:l])) - } - if n > len(names) { - return names, io.EOF - } - return names, nil -} - -// CreateKey creates a key named path under open key k. -// CreateKey returns the new key and a boolean flag that reports -// whether the key already existed. -// The access parameter specifies the access rights for the key -// to be created. -func CreateKey(k Key, path string, access uint32) (newk Key, openedExisting bool, err error) { - var h syscall.Handle - var d uint32 - err = regCreateKeyEx(syscall.Handle(k), syscall.StringToUTF16Ptr(path), - 0, nil, _REG_OPTION_NON_VOLATILE, access, nil, &h, &d) - if err != nil { - return 0, false, err - } - return Key(h), d == _REG_OPENED_EXISTING_KEY, nil -} - -// DeleteKey deletes the subkey path of key k and its values. -func DeleteKey(k Key, path string) error { - return regDeleteKey(syscall.Handle(k), syscall.StringToUTF16Ptr(path)) -} - -// A KeyInfo describes the statistics of a key. It is returned by Stat. -type KeyInfo struct { - SubKeyCount uint32 - MaxSubKeyLen uint32 // size of the key's subkey with the longest name, in Unicode characters, not including the terminating zero byte - ValueCount uint32 - MaxValueNameLen uint32 // size of the key's longest value name, in Unicode characters, not including the terminating zero byte - MaxValueLen uint32 // longest data component among the key's values, in bytes - lastWriteTime syscall.Filetime -} - -// ModTime returns the key's last write time. -func (ki *KeyInfo) ModTime() time.Time { - return time.Unix(0, ki.lastWriteTime.Nanoseconds()) -} - -// Stat retrieves information about the open key k. -func (k Key) Stat() (*KeyInfo, error) { - var ki KeyInfo - err := syscall.RegQueryInfoKey(syscall.Handle(k), nil, nil, nil, - &ki.SubKeyCount, &ki.MaxSubKeyLen, nil, &ki.ValueCount, - &ki.MaxValueNameLen, &ki.MaxValueLen, nil, &ki.lastWriteTime) - if err != nil { - return nil, err - } - return &ki, nil -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/registry/registry_test.go b/Godeps/_workspace/src/golang.org/x/sys/windows/registry/registry_test.go deleted file mode 100644 index df9da07..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/registry/registry_test.go +++ /dev/null @@ -1,682 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package registry_test - -import ( - "bytes" - "crypto/rand" - "os" - "syscall" - "testing" - "time" - - "golang.org/x/sys/windows/registry" -) - -func randKeyName(prefix string) string { - const numbers = "0123456789" - buf := make([]byte, 10) - rand.Read(buf) - for i, b := range buf { - buf[i] = numbers[b%byte(len(numbers))] - } - return prefix + string(buf) -} - -func TestReadSubKeyNames(t *testing.T) { - k, err := registry.OpenKey(registry.CLASSES_ROOT, "TypeLib", registry.ENUMERATE_SUB_KEYS|registry.QUERY_VALUE) - if err != nil { - t.Fatal(err) - } - defer k.Close() - - names, err := k.ReadSubKeyNames(-1) - if err != nil { - t.Fatal(err) - } - var foundStdOle bool - for _, name := range names { - // Every PC has "stdole 2.0 OLE Automation" library installed. - if name == "{00020430-0000-0000-C000-000000000046}" { - foundStdOle = true - } - } - if !foundStdOle { - t.Fatal("could not find stdole 2.0 OLE Automation") - } -} - -func TestCreateOpenDeleteKey(t *testing.T) { - k, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE) - if err != nil { - t.Fatal(err) - } - defer k.Close() - - testKName := randKeyName("TestCreateOpenDeleteKey_") - - testK, exist, err := registry.CreateKey(k, testKName, registry.CREATE_SUB_KEY) - if err != nil { - t.Fatal(err) - } - defer testK.Close() - - if exist { - t.Fatalf("key %q already exists", testKName) - } - - testKAgain, exist, err := registry.CreateKey(k, testKName, registry.CREATE_SUB_KEY) - if err != nil { - t.Fatal(err) - } - defer testKAgain.Close() - - if !exist { - t.Fatalf("key %q should already exist", testKName) - } - - testKOpened, err := registry.OpenKey(k, testKName, registry.ENUMERATE_SUB_KEYS) - if err != nil { - t.Fatal(err) - } - defer testKOpened.Close() - - err = registry.DeleteKey(k, testKName) - if err != nil { - t.Fatal(err) - } - - testKOpenedAgain, err := registry.OpenKey(k, testKName, registry.ENUMERATE_SUB_KEYS) - if err == nil { - defer testKOpenedAgain.Close() - t.Fatalf("key %q should already been deleted", testKName) - } - if err != registry.ErrNotExist { - t.Fatalf(`unexpected error ("not exist" expected): %v`, err) - } -} - -func equalStringSlice(a, b []string) bool { - if len(a) != len(b) { - return false - } - if a == nil { - return true - } - for i := range a { - if a[i] != b[i] { - return false - } - } - return true -} - -type ValueTest struct { - Type uint32 - Name string - Value interface{} - WillFail bool -} - -var ValueTests = []ValueTest{ - {Type: registry.SZ, Name: "String1", Value: ""}, - {Type: registry.SZ, Name: "String2", Value: "\000", WillFail: true}, - {Type: registry.SZ, Name: "String3", Value: "Hello World"}, - {Type: registry.SZ, Name: "String4", Value: "Hello World\000", WillFail: true}, - {Type: registry.EXPAND_SZ, Name: "ExpString1", Value: ""}, - {Type: registry.EXPAND_SZ, Name: "ExpString2", Value: "\000", WillFail: true}, - {Type: registry.EXPAND_SZ, Name: "ExpString3", Value: "Hello World"}, - {Type: registry.EXPAND_SZ, Name: "ExpString4", Value: "Hello\000World", WillFail: true}, - {Type: registry.EXPAND_SZ, Name: "ExpString5", Value: "%PATH%"}, - {Type: registry.EXPAND_SZ, Name: "ExpString6", Value: "%NO_SUCH_VARIABLE%"}, - {Type: registry.EXPAND_SZ, Name: "ExpString7", Value: "%PATH%;."}, - {Type: registry.BINARY, Name: "Binary1", Value: []byte{}}, - {Type: registry.BINARY, Name: "Binary2", Value: []byte{1, 2, 3}}, - {Type: registry.BINARY, Name: "Binary3", Value: []byte{3, 2, 1, 0, 1, 2, 3}}, - {Type: registry.DWORD, Name: "Dword1", Value: uint64(0)}, - {Type: registry.DWORD, Name: "Dword2", Value: uint64(1)}, - {Type: registry.DWORD, Name: "Dword3", Value: uint64(0xff)}, - {Type: registry.DWORD, Name: "Dword4", Value: uint64(0xffff)}, - {Type: registry.QWORD, Name: "Qword1", Value: uint64(0)}, - {Type: registry.QWORD, Name: "Qword2", Value: uint64(1)}, - {Type: registry.QWORD, Name: "Qword3", Value: uint64(0xff)}, - {Type: registry.QWORD, Name: "Qword4", Value: uint64(0xffff)}, - {Type: registry.QWORD, Name: "Qword5", Value: uint64(0xffffff)}, - {Type: registry.QWORD, Name: "Qword6", Value: uint64(0xffffffff)}, - {Type: registry.MULTI_SZ, Name: "MultiString1", Value: []string{"a", "b", "c"}}, - {Type: registry.MULTI_SZ, Name: "MultiString2", Value: []string{"abc", "", "cba"}}, - {Type: registry.MULTI_SZ, Name: "MultiString3", Value: []string{""}}, - {Type: registry.MULTI_SZ, Name: "MultiString4", Value: []string{"abcdef"}}, - {Type: registry.MULTI_SZ, Name: "MultiString5", Value: []string{"\000"}, WillFail: true}, - {Type: registry.MULTI_SZ, Name: "MultiString6", Value: []string{"a\000b"}, WillFail: true}, - {Type: registry.MULTI_SZ, Name: "MultiString7", Value: []string{"ab", "\000", "cd"}, WillFail: true}, - {Type: registry.MULTI_SZ, Name: "MultiString8", Value: []string{"\000", "cd"}, WillFail: true}, - {Type: registry.MULTI_SZ, Name: "MultiString9", Value: []string{"ab", "\000"}, WillFail: true}, -} - -func setValues(t *testing.T, k registry.Key) { - for _, test := range ValueTests { - var err error - switch test.Type { - case registry.SZ: - err = k.SetStringValue(test.Name, test.Value.(string)) - case registry.EXPAND_SZ: - err = k.SetExpandStringValue(test.Name, test.Value.(string)) - case registry.MULTI_SZ: - err = k.SetStringsValue(test.Name, test.Value.([]string)) - case registry.BINARY: - err = k.SetBinaryValue(test.Name, test.Value.([]byte)) - case registry.DWORD: - err = k.SetDWordValue(test.Name, uint32(test.Value.(uint64))) - case registry.QWORD: - err = k.SetQWordValue(test.Name, test.Value.(uint64)) - default: - t.Fatalf("unsupported type %d for %s value", test.Type, test.Name) - } - if test.WillFail { - if err == nil { - t.Fatalf("setting %s value %q should fail, but succeeded", test.Name, test.Value) - } - } else { - if err != nil { - t.Fatal(err) - } - } - } -} - -func enumerateValues(t *testing.T, k registry.Key) { - names, err := k.ReadValueNames(-1) - if err != nil { - t.Error(err) - return - } - haveNames := make(map[string]bool) - for _, n := range names { - haveNames[n] = false - } - for _, test := range ValueTests { - wantFound := !test.WillFail - _, haveFound := haveNames[test.Name] - if wantFound && !haveFound { - t.Errorf("value %s is not found while enumerating", test.Name) - } - if haveFound && !wantFound { - t.Errorf("value %s is found while enumerating, but expected to fail", test.Name) - } - if haveFound { - delete(haveNames, test.Name) - } - } - for n, v := range haveNames { - t.Errorf("value %s (%v) is found while enumerating, but has not been cretaed", n, v) - } -} - -func testErrNotExist(t *testing.T, name string, err error) { - if err == nil { - t.Errorf("%s value should not exist", name) - return - } - if err != registry.ErrNotExist { - t.Errorf("reading %s value should return 'not exist' error, but got: %s", name, err) - return - } -} - -func testErrUnexpectedType(t *testing.T, test ValueTest, gottype uint32, err error) { - if err == nil { - t.Errorf("GetXValue(%q) should not succeed", test.Name) - return - } - if err != registry.ErrUnexpectedType { - t.Errorf("reading %s value should return 'unexpected key value type' error, but got: %s", test.Name, err) - return - } - if gottype != test.Type { - t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) - return - } -} - -func testGetStringValue(t *testing.T, k registry.Key, test ValueTest) { - got, gottype, err := k.GetStringValue(test.Name) - if err != nil { - t.Errorf("GetStringValue(%s) failed: %v", test.Name, err) - return - } - if got != test.Value { - t.Errorf("want %s value %q, got %q", test.Name, test.Value, got) - return - } - if gottype != test.Type { - t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) - return - } - if gottype == registry.EXPAND_SZ { - _, err = registry.ExpandString(got) - if err != nil { - t.Errorf("ExpandString(%s) failed: %v", got, err) - return - } - } -} - -func testGetIntegerValue(t *testing.T, k registry.Key, test ValueTest) { - got, gottype, err := k.GetIntegerValue(test.Name) - if err != nil { - t.Errorf("GetIntegerValue(%s) failed: %v", test.Name, err) - return - } - if got != test.Value.(uint64) { - t.Errorf("want %s value %v, got %v", test.Name, test.Value, got) - return - } - if gottype != test.Type { - t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) - return - } -} - -func testGetBinaryValue(t *testing.T, k registry.Key, test ValueTest) { - got, gottype, err := k.GetBinaryValue(test.Name) - if err != nil { - t.Errorf("GetBinaryValue(%s) failed: %v", test.Name, err) - return - } - if !bytes.Equal(got, test.Value.([]byte)) { - t.Errorf("want %s value %v, got %v", test.Name, test.Value, got) - return - } - if gottype != test.Type { - t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) - return - } -} - -func testGetStringsValue(t *testing.T, k registry.Key, test ValueTest) { - got, gottype, err := k.GetStringsValue(test.Name) - if err != nil { - t.Errorf("GetStringsValue(%s) failed: %v", test.Name, err) - return - } - if !equalStringSlice(got, test.Value.([]string)) { - t.Errorf("want %s value %#v, got %#v", test.Name, test.Value, got) - return - } - if gottype != test.Type { - t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) - return - } -} - -func testGetValue(t *testing.T, k registry.Key, test ValueTest, size int) { - if size <= 0 { - return - } - // read data with no buffer - gotsize, gottype, err := k.GetValue(test.Name, nil) - if err != nil { - t.Errorf("GetValue(%s, [%d]byte) failed: %v", test.Name, size, err) - return - } - if gotsize != size { - t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize) - return - } - if gottype != test.Type { - t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) - return - } - // read data with short buffer - gotsize, gottype, err = k.GetValue(test.Name, make([]byte, size-1)) - if err == nil { - t.Errorf("GetValue(%s, [%d]byte) should fail, but suceeded", test.Name, size-1) - return - } - if err != registry.ErrShortBuffer { - t.Errorf("reading %s value should return 'short buffer' error, but got: %s", test.Name, err) - return - } - if gotsize != size { - t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize) - return - } - if gottype != test.Type { - t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) - return - } - // read full data - gotsize, gottype, err = k.GetValue(test.Name, make([]byte, size)) - if err != nil { - t.Errorf("GetValue(%s, [%d]byte) failed: %v", test.Name, size, err) - return - } - if gotsize != size { - t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize) - return - } - if gottype != test.Type { - t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) - return - } - // check GetValue returns ErrNotExist as required - _, _, err = k.GetValue(test.Name+"_not_there", make([]byte, size)) - if err == nil { - t.Errorf("GetValue(%q) should not succeed", test.Name) - return - } - if err != registry.ErrNotExist { - t.Errorf("GetValue(%q) should return 'not exist' error, but got: %s", test.Name, err) - return - } -} - -func testValues(t *testing.T, k registry.Key) { - for _, test := range ValueTests { - switch test.Type { - case registry.SZ, registry.EXPAND_SZ: - if test.WillFail { - _, _, err := k.GetStringValue(test.Name) - testErrNotExist(t, test.Name, err) - } else { - testGetStringValue(t, k, test) - _, gottype, err := k.GetIntegerValue(test.Name) - testErrUnexpectedType(t, test, gottype, err) - // Size of utf16 string in bytes is not perfect, - // but correct for current test values. - // Size also includes terminating 0. - testGetValue(t, k, test, (len(test.Value.(string))+1)*2) - } - _, _, err := k.GetStringValue(test.Name + "_string_not_created") - testErrNotExist(t, test.Name+"_string_not_created", err) - case registry.DWORD, registry.QWORD: - testGetIntegerValue(t, k, test) - _, gottype, err := k.GetBinaryValue(test.Name) - testErrUnexpectedType(t, test, gottype, err) - _, _, err = k.GetIntegerValue(test.Name + "_int_not_created") - testErrNotExist(t, test.Name+"_int_not_created", err) - size := 8 - if test.Type == registry.DWORD { - size = 4 - } - testGetValue(t, k, test, size) - case registry.BINARY: - testGetBinaryValue(t, k, test) - _, gottype, err := k.GetStringsValue(test.Name) - testErrUnexpectedType(t, test, gottype, err) - _, _, err = k.GetBinaryValue(test.Name + "_byte_not_created") - testErrNotExist(t, test.Name+"_byte_not_created", err) - testGetValue(t, k, test, len(test.Value.([]byte))) - case registry.MULTI_SZ: - if test.WillFail { - _, _, err := k.GetStringsValue(test.Name) - testErrNotExist(t, test.Name, err) - } else { - testGetStringsValue(t, k, test) - _, gottype, err := k.GetStringValue(test.Name) - testErrUnexpectedType(t, test, gottype, err) - size := 0 - for _, s := range test.Value.([]string) { - size += len(s) + 1 // nil terminated - } - size += 1 // extra nil at the end - size *= 2 // count bytes, not uint16 - testGetValue(t, k, test, size) - } - _, _, err := k.GetStringsValue(test.Name + "_strings_not_created") - testErrNotExist(t, test.Name+"_strings_not_created", err) - default: - t.Errorf("unsupported type %d for %s value", test.Type, test.Name) - continue - } - } -} - -func testStat(t *testing.T, k registry.Key) { - subk, _, err := registry.CreateKey(k, "subkey", registry.CREATE_SUB_KEY) - if err != nil { - t.Error(err) - return - } - defer subk.Close() - - defer registry.DeleteKey(k, "subkey") - - ki, err := k.Stat() - if err != nil { - t.Error(err) - return - } - if ki.SubKeyCount != 1 { - t.Error("key must have 1 subkey") - } - if ki.MaxSubKeyLen != 6 { - t.Error("key max subkey name length must be 6") - } - if ki.ValueCount != 24 { - t.Errorf("key must have 24 values, but is %d", ki.ValueCount) - } - if ki.MaxValueNameLen != 12 { - t.Errorf("key max value name length must be 10, but is %d", ki.MaxValueNameLen) - } - if ki.MaxValueLen != 38 { - t.Errorf("key max value length must be 38, but is %d", ki.MaxValueLen) - } - if mt, ct := ki.ModTime(), time.Now(); ct.Sub(mt) > 100*time.Millisecond { - t.Errorf("key mod time is not close to current time: mtime=%v current=%v delta=%v", mt, ct, ct.Sub(mt)) - } -} - -func deleteValues(t *testing.T, k registry.Key) { - for _, test := range ValueTests { - if test.WillFail { - continue - } - err := k.DeleteValue(test.Name) - if err != nil { - t.Error(err) - continue - } - } - names, err := k.ReadValueNames(-1) - if err != nil { - t.Error(err) - return - } - if len(names) != 0 { - t.Errorf("some values remain after deletion: %v", names) - } -} - -func TestValues(t *testing.T) { - softwareK, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE) - if err != nil { - t.Fatal(err) - } - defer softwareK.Close() - - testKName := randKeyName("TestValues_") - - k, exist, err := registry.CreateKey(softwareK, testKName, registry.CREATE_SUB_KEY|registry.QUERY_VALUE|registry.SET_VALUE) - if err != nil { - t.Fatal(err) - } - defer k.Close() - - if exist { - t.Fatalf("key %q already exists", testKName) - } - - defer registry.DeleteKey(softwareK, testKName) - - setValues(t, k) - - enumerateValues(t, k) - - testValues(t, k) - - testStat(t, k) - - deleteValues(t, k) -} - -func walkKey(t *testing.T, k registry.Key, kname string) { - names, err := k.ReadValueNames(-1) - if err != nil { - t.Fatalf("reading value names of %s failed: %v", kname, err) - } - for _, name := range names { - _, valtype, err := k.GetValue(name, nil) - if err != nil { - t.Fatalf("reading value type of %s of %s failed: %v", name, kname, err) - } - switch valtype { - case registry.NONE: - case registry.SZ: - _, _, err := k.GetStringValue(name) - if err != nil { - t.Error(err) - } - case registry.EXPAND_SZ: - s, _, err := k.GetStringValue(name) - if err != nil { - t.Error(err) - } - _, err = registry.ExpandString(s) - if err != nil { - t.Error(err) - } - case registry.DWORD, registry.QWORD: - _, _, err := k.GetIntegerValue(name) - if err != nil { - t.Error(err) - } - case registry.BINARY: - _, _, err := k.GetBinaryValue(name) - if err != nil { - t.Error(err) - } - case registry.MULTI_SZ: - _, _, err := k.GetStringsValue(name) - if err != nil { - t.Error(err) - } - case registry.FULL_RESOURCE_DESCRIPTOR, registry.RESOURCE_LIST, registry.RESOURCE_REQUIREMENTS_LIST: - // TODO: not implemented - default: - t.Fatalf("value type %d of %s of %s failed: %v", valtype, name, kname, err) - } - } - - names, err = k.ReadSubKeyNames(-1) - if err != nil { - t.Fatalf("reading sub-keys of %s failed: %v", kname, err) - } - for _, name := range names { - func() { - subk, err := registry.OpenKey(k, name, registry.ENUMERATE_SUB_KEYS|registry.QUERY_VALUE) - if err != nil { - if err == syscall.ERROR_ACCESS_DENIED { - // ignore error, if we are not allowed to access this key - return - } - t.Fatalf("opening sub-keys %s of %s failed: %v", name, kname, err) - } - defer subk.Close() - - walkKey(t, subk, kname+`\`+name) - }() - } -} - -func TestWalkFullRegistry(t *testing.T) { - if testing.Short() { - t.Skip("skipping long running test in short mode") - } - walkKey(t, registry.CLASSES_ROOT, "CLASSES_ROOT") - walkKey(t, registry.CURRENT_USER, "CURRENT_USER") - walkKey(t, registry.LOCAL_MACHINE, "LOCAL_MACHINE") - walkKey(t, registry.USERS, "USERS") - walkKey(t, registry.CURRENT_CONFIG, "CURRENT_CONFIG") -} - -func TestExpandString(t *testing.T) { - got, err := registry.ExpandString("%PATH%") - if err != nil { - t.Fatal(err) - } - want := os.Getenv("PATH") - if got != want { - t.Errorf("want %q string expanded, got %q", want, got) - } -} - -func TestInvalidValues(t *testing.T) { - softwareK, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE) - if err != nil { - t.Fatal(err) - } - defer softwareK.Close() - - testKName := randKeyName("TestInvalidValues_") - - k, exist, err := registry.CreateKey(softwareK, testKName, registry.CREATE_SUB_KEY|registry.QUERY_VALUE|registry.SET_VALUE) - if err != nil { - t.Fatal(err) - } - defer k.Close() - - if exist { - t.Fatalf("key %q already exists", testKName) - } - - defer registry.DeleteKey(softwareK, testKName) - - var tests = []struct { - Type uint32 - Name string - Data []byte - }{ - {registry.DWORD, "Dword1", nil}, - {registry.DWORD, "Dword2", []byte{1, 2, 3}}, - {registry.QWORD, "Qword1", nil}, - {registry.QWORD, "Qword2", []byte{1, 2, 3}}, - {registry.QWORD, "Qword3", []byte{1, 2, 3, 4, 5, 6, 7}}, - {registry.MULTI_SZ, "MultiString1", nil}, - {registry.MULTI_SZ, "MultiString2", []byte{0}}, - {registry.MULTI_SZ, "MultiString3", []byte{'a', 'b', 0}}, - {registry.MULTI_SZ, "MultiString4", []byte{'a', 0, 0, 'b', 0}}, - {registry.MULTI_SZ, "MultiString5", []byte{'a', 0, 0}}, - } - - for _, test := range tests { - err := k.SetValue(test.Name, test.Type, test.Data) - if err != nil { - t.Fatalf("SetValue for %q failed: %v", test.Name, err) - } - } - - for _, test := range tests { - switch test.Type { - case registry.DWORD, registry.QWORD: - value, valType, err := k.GetIntegerValue(test.Name) - if err == nil { - t.Errorf("GetIntegerValue(%q) succeeded. Returns type=%d value=%v", test.Name, valType, value) - } - case registry.MULTI_SZ: - value, valType, err := k.GetStringsValue(test.Name) - if err == nil { - if len(value) != 0 { - t.Errorf("GetStringsValue(%q) succeeded. Returns type=%d value=%v", test.Name, valType, value) - } - } - default: - t.Errorf("unsupported type %d for %s value", test.Type, test.Name) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/registry/syscall.go b/Godeps/_workspace/src/golang.org/x/sys/windows/registry/syscall.go deleted file mode 100644 index 38e573f..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/registry/syscall.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package registry - -import "syscall" - -//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go syscall.go - -const ( - _REG_OPTION_NON_VOLATILE = 0 - - _REG_CREATED_NEW_KEY = 1 - _REG_OPENED_EXISTING_KEY = 2 - - _ERROR_NO_MORE_ITEMS syscall.Errno = 259 -) - -//sys regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) = advapi32.RegCreateKeyExW -//sys regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) = advapi32.RegDeleteKeyW -//sys regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) = advapi32.RegSetValueExW -//sys regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegEnumValueW -//sys regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) = advapi32.RegDeleteValueW - -//sys expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/registry/value.go b/Godeps/_workspace/src/golang.org/x/sys/windows/registry/value.go deleted file mode 100644 index bb45a23..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/registry/value.go +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package registry - -import ( - "errors" - "io" - "syscall" - "unicode/utf16" - "unsafe" -) - -const ( - // Registry value types. - NONE = 0 - SZ = 1 - EXPAND_SZ = 2 - BINARY = 3 - DWORD = 4 - DWORD_BIG_ENDIAN = 5 - LINK = 6 - MULTI_SZ = 7 - RESOURCE_LIST = 8 - FULL_RESOURCE_DESCRIPTOR = 9 - RESOURCE_REQUIREMENTS_LIST = 10 - QWORD = 11 -) - -var ( - // ErrShortBuffer is returned when the buffer was too short for the operation. - ErrShortBuffer = syscall.ERROR_MORE_DATA - - // ErrNotExist is returned when a registry key or value does not exist. - ErrNotExist = syscall.ERROR_FILE_NOT_FOUND - - // ErrUnexpectedType is returned by Get*Value when the value's type was unexpected. - ErrUnexpectedType = errors.New("unexpected key value type") -) - -// GetValue retrieves the type and data for the specified value associated -// with an open key k. It fills up buffer buf and returns the retrieved -// byte count n. If buf is too small to fit the stored value it returns -// ErrShortBuffer error along with the required buffer size n. -// If no buffer is provided, it returns true and actual buffer size n. -// If no buffer is provided, GetValue returns the value's type only. -// If the value does not exist, the error returned is ErrNotExist. -// -// GetValue is a low level function. If value's type is known, use the appropriate -// Get*Value function instead. -func (k Key) GetValue(name string, buf []byte) (n int, valtype uint32, err error) { - pname, err := syscall.UTF16PtrFromString(name) - if err != nil { - return 0, 0, err - } - var pbuf *byte - if len(buf) > 0 { - pbuf = (*byte)(unsafe.Pointer(&buf[0])) - } - l := uint32(len(buf)) - err = syscall.RegQueryValueEx(syscall.Handle(k), pname, nil, &valtype, pbuf, &l) - if err != nil { - return int(l), valtype, err - } - return int(l), valtype, nil -} - -func (k Key) getValue(name string, buf []byte) (date []byte, valtype uint32, err error) { - p, err := syscall.UTF16PtrFromString(name) - if err != nil { - return nil, 0, err - } - var t uint32 - n := uint32(len(buf)) - for { - err = syscall.RegQueryValueEx(syscall.Handle(k), p, nil, &t, (*byte)(unsafe.Pointer(&buf[0])), &n) - if err == nil { - return buf[:n], t, nil - } - if err != syscall.ERROR_MORE_DATA { - return nil, 0, err - } - if n <= uint32(len(buf)) { - return nil, 0, err - } - buf = make([]byte, n) - } -} - -// GetStringValue retrieves the string value for the specified -// value name associated with an open key k. It also returns the value's type. -// If value does not exist, GetStringValue returns ErrNotExist. -// If value is not SZ or EXPAND_SZ, it will return the correct value -// type and ErrUnexpectedType. -func (k Key) GetStringValue(name string) (val string, valtype uint32, err error) { - data, typ, err2 := k.getValue(name, make([]byte, 64)) - if err2 != nil { - return "", typ, err2 - } - switch typ { - case SZ, EXPAND_SZ: - default: - return "", typ, ErrUnexpectedType - } - if len(data) == 0 { - return "", typ, nil - } - u := (*[1 << 10]uint16)(unsafe.Pointer(&data[0]))[:] - return syscall.UTF16ToString(u), typ, nil -} - -// ExpandString expands environment-variable strings and replaces -// them with the values defined for the current user. -// Use ExpandString to expand EXPAND_SZ strings. -func ExpandString(value string) (string, error) { - if value == "" { - return "", nil - } - p, err := syscall.UTF16PtrFromString(value) - if err != nil { - return "", err - } - r := make([]uint16, 100) - for { - n, err := expandEnvironmentStrings(p, &r[0], uint32(len(r))) - if err != nil { - return "", err - } - if n <= uint32(len(r)) { - u := (*[1 << 15]uint16)(unsafe.Pointer(&r[0]))[:] - return syscall.UTF16ToString(u), nil - } - r = make([]uint16, n) - } -} - -// GetStringsValue retrieves the []string value for the specified -// value name associated with an open key k. It also returns the value's type. -// If value does not exist, GetStringsValue returns ErrNotExist. -// If value is not MULTI_SZ, it will return the correct value -// type and ErrUnexpectedType. -func (k Key) GetStringsValue(name string) (val []string, valtype uint32, err error) { - data, typ, err2 := k.getValue(name, make([]byte, 64)) - if err2 != nil { - return nil, typ, err2 - } - if typ != MULTI_SZ { - return nil, typ, ErrUnexpectedType - } - if len(data) == 0 { - return nil, typ, nil - } - p := (*[1 << 24]uint16)(unsafe.Pointer(&data[0]))[:len(data)/2] - if len(p) == 0 { - return nil, typ, nil - } - if p[len(p)-1] == 0 { - p = p[:len(p)-1] // remove terminating null - } - val = make([]string, 0, 5) - from := 0 - for i, c := range p { - if c == 0 { - val = append(val, string(utf16.Decode(p[from:i]))) - from = i + 1 - } - } - return val, typ, nil -} - -// GetIntegerValue retrieves the integer value for the specified -// value name associated with an open key k. It also returns the value's type. -// If value does not exist, GetIntegerValue returns ErrNotExist. -// If value is not DWORD or QWORD, it will return the correct value -// type and ErrUnexpectedType. -func (k Key) GetIntegerValue(name string) (val uint64, valtype uint32, err error) { - data, typ, err2 := k.getValue(name, make([]byte, 8)) - if err2 != nil { - return 0, typ, err2 - } - switch typ { - case DWORD: - if len(data) != 4 { - return 0, typ, errors.New("DWORD value is not 4 bytes long") - } - return uint64(*(*uint32)(unsafe.Pointer(&data[0]))), DWORD, nil - case QWORD: - if len(data) != 8 { - return 0, typ, errors.New("QWORD value is not 8 bytes long") - } - return uint64(*(*uint64)(unsafe.Pointer(&data[0]))), QWORD, nil - default: - return 0, typ, ErrUnexpectedType - } -} - -// GetBinaryValue retrieves the binary value for the specified -// value name associated with an open key k. It also returns the value's type. -// If value does not exist, GetBinaryValue returns ErrNotExist. -// If value is not BINARY, it will return the correct value -// type and ErrUnexpectedType. -func (k Key) GetBinaryValue(name string) (val []byte, valtype uint32, err error) { - data, typ, err2 := k.getValue(name, make([]byte, 64)) - if err2 != nil { - return nil, typ, err2 - } - if typ != BINARY { - return nil, typ, ErrUnexpectedType - } - return data, typ, nil -} - -func (k Key) setValue(name string, valtype uint32, data []byte) error { - p, err := syscall.UTF16PtrFromString(name) - if err != nil { - return err - } - if len(data) == 0 { - return regSetValueEx(syscall.Handle(k), p, 0, valtype, nil, 0) - } - return regSetValueEx(syscall.Handle(k), p, 0, valtype, &data[0], uint32(len(data))) -} - -// SetDWordValue sets the data and type of a name value -// under key k to value and DWORD. -func (k Key) SetDWordValue(name string, value uint32) error { - return k.setValue(name, DWORD, (*[4]byte)(unsafe.Pointer(&value))[:]) -} - -// SetQWordValue sets the data and type of a name value -// under key k to value and QWORD. -func (k Key) SetQWordValue(name string, value uint64) error { - return k.setValue(name, QWORD, (*[8]byte)(unsafe.Pointer(&value))[:]) -} - -func (k Key) setStringValue(name string, valtype uint32, value string) error { - v, err := syscall.UTF16FromString(value) - if err != nil { - return err - } - buf := (*[1 << 10]byte)(unsafe.Pointer(&v[0]))[:len(v)*2] - return k.setValue(name, valtype, buf) -} - -// SetStringValue sets the data and type of a name value -// under key k to value and SZ. The value must not contain a zero byte. -func (k Key) SetStringValue(name, value string) error { - return k.setStringValue(name, SZ, value) -} - -// SetExpandStringValue sets the data and type of a name value -// under key k to value and EXPAND_SZ. The value must not contain a zero byte. -func (k Key) SetExpandStringValue(name, value string) error { - return k.setStringValue(name, EXPAND_SZ, value) -} - -// SetStringsValue sets the data and type of a name value -// under key k to value and MULTI_SZ. The value strings -// must not contain a zero byte. -func (k Key) SetStringsValue(name string, value []string) error { - ss := "" - for _, s := range value { - for i := 0; i < len(s); i++ { - if s[i] == 0 { - return errors.New("string cannot have 0 inside") - } - } - ss += s + "\x00" - } - v := utf16.Encode([]rune(ss + "\x00")) - buf := (*[1 << 10]byte)(unsafe.Pointer(&v[0]))[:len(v)*2] - return k.setValue(name, MULTI_SZ, buf) -} - -// SetBinaryValue sets the data and type of a name value -// under key k to value and BINARY. -func (k Key) SetBinaryValue(name string, value []byte) error { - return k.setValue(name, BINARY, value) -} - -// DeleteValue removes a named value from the key k. -func (k Key) DeleteValue(name string) error { - return regDeleteValue(syscall.Handle(k), syscall.StringToUTF16Ptr(name)) -} - -// ReadValueNames returns the value names of key k. -// The parameter n controls the number of returned names, -// analogous to the way os.File.Readdirnames works. -func (k Key) ReadValueNames(n int) ([]string, error) { - ki, err := k.Stat() - if err != nil { - return nil, err - } - names := make([]string, 0, ki.ValueCount) - buf := make([]uint16, ki.MaxValueNameLen+1) // extra room for terminating null character -loopItems: - for i := uint32(0); ; i++ { - if n > 0 { - if len(names) == n { - return names, nil - } - } - l := uint32(len(buf)) - for { - err := regEnumValue(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil) - if err == nil { - break - } - if err == syscall.ERROR_MORE_DATA { - println(len(buf), l) - // Double buffer size and try again. - l = uint32(2 * len(buf)) - buf = make([]uint16, l) - continue - } - if err == _ERROR_NO_MORE_ITEMS { - break loopItems - } - return names, err - } - names = append(names, syscall.UTF16ToString(buf[:l])) - } - if n > len(names) { - return names, io.EOF - } - return names, nil -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/registry/zsyscall_windows.go b/Godeps/_workspace/src/golang.org/x/sys/windows/registry/zsyscall_windows.go deleted file mode 100644 index 2b3de63..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/registry/zsyscall_windows.go +++ /dev/null @@ -1,73 +0,0 @@ -// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT - -package registry - -import "unsafe" -import "syscall" - -var _ unsafe.Pointer - -var ( - modadvapi32 = syscall.NewLazyDLL("advapi32.dll") - modkernel32 = syscall.NewLazyDLL("kernel32.dll") - - procRegCreateKeyExW = modadvapi32.NewProc("RegCreateKeyExW") - procRegDeleteKeyW = modadvapi32.NewProc("RegDeleteKeyW") - procRegSetValueExW = modadvapi32.NewProc("RegSetValueExW") - procRegEnumValueW = modadvapi32.NewProc("RegEnumValueW") - procRegDeleteValueW = modadvapi32.NewProc("RegDeleteValueW") - procExpandEnvironmentStringsW = modkernel32.NewProc("ExpandEnvironmentStringsW") -) - -func regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) { - r0, _, _ := syscall.Syscall9(procRegCreateKeyExW.Addr(), 9, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(reserved), uintptr(unsafe.Pointer(class)), uintptr(options), uintptr(desired), uintptr(unsafe.Pointer(sa)), uintptr(unsafe.Pointer(result)), uintptr(unsafe.Pointer(disposition))) - if r0 != 0 { - regerrno = syscall.Errno(r0) - } - return -} - -func regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) { - r0, _, _ := syscall.Syscall(procRegDeleteKeyW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(subkey)), 0) - if r0 != 0 { - regerrno = syscall.Errno(r0) - } - return -} - -func regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) { - r0, _, _ := syscall.Syscall6(procRegSetValueExW.Addr(), 6, uintptr(key), uintptr(unsafe.Pointer(valueName)), uintptr(reserved), uintptr(vtype), uintptr(unsafe.Pointer(buf)), uintptr(bufsize)) - if r0 != 0 { - regerrno = syscall.Errno(r0) - } - return -} - -func regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) { - r0, _, _ := syscall.Syscall9(procRegEnumValueW.Addr(), 8, uintptr(key), uintptr(index), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen)), 0) - if r0 != 0 { - regerrno = syscall.Errno(r0) - } - return -} - -func regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) { - r0, _, _ := syscall.Syscall(procRegDeleteValueW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(name)), 0) - if r0 != 0 { - regerrno = syscall.Errno(r0) - } - return -} - -func expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) { - r0, _, e1 := syscall.Syscall(procExpandEnvironmentStringsW.Addr(), 3, uintptr(unsafe.Pointer(src)), uintptr(unsafe.Pointer(dst)), uintptr(size)) - n = uint32(r0) - if n == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/security_windows.go b/Godeps/_workspace/src/golang.org/x/sys/windows/security_windows.go deleted file mode 100644 index ca09bdd..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/security_windows.go +++ /dev/null @@ -1,435 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package windows - -import ( - "syscall" - "unsafe" -) - -const ( - STANDARD_RIGHTS_REQUIRED = 0xf0000 - STANDARD_RIGHTS_READ = 0x20000 - STANDARD_RIGHTS_WRITE = 0x20000 - STANDARD_RIGHTS_EXECUTE = 0x20000 - STANDARD_RIGHTS_ALL = 0x1F0000 -) - -const ( - NameUnknown = 0 - NameFullyQualifiedDN = 1 - NameSamCompatible = 2 - NameDisplay = 3 - NameUniqueId = 6 - NameCanonical = 7 - NameUserPrincipal = 8 - NameCanonicalEx = 9 - NameServicePrincipal = 10 - NameDnsDomain = 12 -) - -// This function returns 1 byte BOOLEAN rather than the 4 byte BOOL. -// http://blogs.msdn.com/b/drnick/archive/2007/12/19/windows-and-upn-format-credentials.aspx -//sys TranslateName(accName *uint16, accNameFormat uint32, desiredNameFormat uint32, translatedName *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.TranslateNameW -//sys GetUserNameEx(nameFormat uint32, nameBuffre *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.GetUserNameExW - -// TranslateAccountName converts a directory service -// object name from one format to another. -func TranslateAccountName(username string, from, to uint32, initSize int) (string, error) { - u, e := UTF16PtrFromString(username) - if e != nil { - return "", e - } - n := uint32(50) - for { - b := make([]uint16, n) - e = TranslateName(u, from, to, &b[0], &n) - if e == nil { - return UTF16ToString(b[:n]), nil - } - if e != ERROR_INSUFFICIENT_BUFFER { - return "", e - } - if n <= uint32(len(b)) { - return "", e - } - } -} - -const ( - // do not reorder - NetSetupUnknownStatus = iota - NetSetupUnjoined - NetSetupWorkgroupName - NetSetupDomainName -) - -type UserInfo10 struct { - Name *uint16 - Comment *uint16 - UsrComment *uint16 - FullName *uint16 -} - -//sys NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) = netapi32.NetUserGetInfo -//sys NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) = netapi32.NetGetJoinInformation -//sys NetApiBufferFree(buf *byte) (neterr error) = netapi32.NetApiBufferFree - -const ( - // do not reorder - SidTypeUser = 1 + iota - SidTypeGroup - SidTypeDomain - SidTypeAlias - SidTypeWellKnownGroup - SidTypeDeletedAccount - SidTypeInvalid - SidTypeUnknown - SidTypeComputer - SidTypeLabel -) - -type SidIdentifierAuthority struct { - Value [6]byte -} - -var ( - SECURITY_NULL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 0}} - SECURITY_WORLD_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 1}} - SECURITY_LOCAL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 2}} - SECURITY_CREATOR_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 3}} - SECURITY_NON_UNIQUE_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 4}} - SECURITY_NT_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 5}} - SECURITY_MANDATORY_LABEL_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 16}} -) - -const ( - SECURITY_NULL_RID = 0 - SECURITY_WORLD_RID = 0 - SECURITY_LOCAL_RID = 0 - SECURITY_CREATOR_OWNER_RID = 0 - SECURITY_CREATOR_GROUP_RID = 1 - SECURITY_DIALUP_RID = 1 - SECURITY_NETWORK_RID = 2 - SECURITY_BATCH_RID = 3 - SECURITY_INTERACTIVE_RID = 4 - SECURITY_LOGON_IDS_RID = 5 - SECURITY_SERVICE_RID = 6 - SECURITY_LOCAL_SYSTEM_RID = 18 - SECURITY_BUILTIN_DOMAIN_RID = 32 - SECURITY_PRINCIPAL_SELF_RID = 10 - SECURITY_CREATOR_OWNER_SERVER_RID = 0x2 - SECURITY_CREATOR_GROUP_SERVER_RID = 0x3 - SECURITY_LOGON_IDS_RID_COUNT = 0x3 - SECURITY_ANONYMOUS_LOGON_RID = 0x7 - SECURITY_PROXY_RID = 0x8 - SECURITY_ENTERPRISE_CONTROLLERS_RID = 0x9 - SECURITY_SERVER_LOGON_RID = SECURITY_ENTERPRISE_CONTROLLERS_RID - SECURITY_AUTHENTICATED_USER_RID = 0xb - SECURITY_RESTRICTED_CODE_RID = 0xc - SECURITY_NT_NON_UNIQUE_RID = 0x15 -) - -//sys LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountSidW -//sys LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountNameW -//sys ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) = advapi32.ConvertSidToStringSidW -//sys ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) = advapi32.ConvertStringSidToSidW -//sys GetLengthSid(sid *SID) (len uint32) = advapi32.GetLengthSid -//sys CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error) = advapi32.CopySid -//sys AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error) = advapi32.AllocateAndInitializeSid -//sys FreeSid(sid *SID) (err error) [failretval!=0] = advapi32.FreeSid -//sys EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) = advapi32.EqualSid - -// The security identifier (SID) structure is a variable-length -// structure used to uniquely identify users or groups. -type SID struct{} - -// StringToSid converts a string-format security identifier -// sid into a valid, functional sid. -func StringToSid(s string) (*SID, error) { - var sid *SID - p, e := UTF16PtrFromString(s) - if e != nil { - return nil, e - } - e = ConvertStringSidToSid(p, &sid) - if e != nil { - return nil, e - } - defer LocalFree((Handle)(unsafe.Pointer(sid))) - return sid.Copy() -} - -// LookupSID retrieves a security identifier sid for the account -// and the name of the domain on which the account was found. -// System specify target computer to search. -func LookupSID(system, account string) (sid *SID, domain string, accType uint32, err error) { - if len(account) == 0 { - return nil, "", 0, syscall.EINVAL - } - acc, e := UTF16PtrFromString(account) - if e != nil { - return nil, "", 0, e - } - var sys *uint16 - if len(system) > 0 { - sys, e = UTF16PtrFromString(system) - if e != nil { - return nil, "", 0, e - } - } - n := uint32(50) - dn := uint32(50) - for { - b := make([]byte, n) - db := make([]uint16, dn) - sid = (*SID)(unsafe.Pointer(&b[0])) - e = LookupAccountName(sys, acc, sid, &n, &db[0], &dn, &accType) - if e == nil { - return sid, UTF16ToString(db), accType, nil - } - if e != ERROR_INSUFFICIENT_BUFFER { - return nil, "", 0, e - } - if n <= uint32(len(b)) { - return nil, "", 0, e - } - } -} - -// String converts sid to a string format -// suitable for display, storage, or transmission. -func (sid *SID) String() (string, error) { - var s *uint16 - e := ConvertSidToStringSid(sid, &s) - if e != nil { - return "", e - } - defer LocalFree((Handle)(unsafe.Pointer(s))) - return UTF16ToString((*[256]uint16)(unsafe.Pointer(s))[:]), nil -} - -// Len returns the length, in bytes, of a valid security identifier sid. -func (sid *SID) Len() int { - return int(GetLengthSid(sid)) -} - -// Copy creates a duplicate of security identifier sid. -func (sid *SID) Copy() (*SID, error) { - b := make([]byte, sid.Len()) - sid2 := (*SID)(unsafe.Pointer(&b[0])) - e := CopySid(uint32(len(b)), sid2, sid) - if e != nil { - return nil, e - } - return sid2, nil -} - -// LookupAccount retrieves the name of the account for this sid -// and the name of the first domain on which this sid is found. -// System specify target computer to search for. -func (sid *SID) LookupAccount(system string) (account, domain string, accType uint32, err error) { - var sys *uint16 - if len(system) > 0 { - sys, err = UTF16PtrFromString(system) - if err != nil { - return "", "", 0, err - } - } - n := uint32(50) - dn := uint32(50) - for { - b := make([]uint16, n) - db := make([]uint16, dn) - e := LookupAccountSid(sys, sid, &b[0], &n, &db[0], &dn, &accType) - if e == nil { - return UTF16ToString(b), UTF16ToString(db), accType, nil - } - if e != ERROR_INSUFFICIENT_BUFFER { - return "", "", 0, e - } - if n <= uint32(len(b)) { - return "", "", 0, e - } - } -} - -const ( - // do not reorder - TOKEN_ASSIGN_PRIMARY = 1 << iota - TOKEN_DUPLICATE - TOKEN_IMPERSONATE - TOKEN_QUERY - TOKEN_QUERY_SOURCE - TOKEN_ADJUST_PRIVILEGES - TOKEN_ADJUST_GROUPS - TOKEN_ADJUST_DEFAULT - - TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | - TOKEN_ASSIGN_PRIMARY | - TOKEN_DUPLICATE | - TOKEN_IMPERSONATE | - TOKEN_QUERY | - TOKEN_QUERY_SOURCE | - TOKEN_ADJUST_PRIVILEGES | - TOKEN_ADJUST_GROUPS | - TOKEN_ADJUST_DEFAULT - TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY - TOKEN_WRITE = STANDARD_RIGHTS_WRITE | - TOKEN_ADJUST_PRIVILEGES | - TOKEN_ADJUST_GROUPS | - TOKEN_ADJUST_DEFAULT - TOKEN_EXECUTE = STANDARD_RIGHTS_EXECUTE -) - -const ( - // do not reorder - TokenUser = 1 + iota - TokenGroups - TokenPrivileges - TokenOwner - TokenPrimaryGroup - TokenDefaultDacl - TokenSource - TokenType - TokenImpersonationLevel - TokenStatistics - TokenRestrictedSids - TokenSessionId - TokenGroupsAndPrivileges - TokenSessionReference - TokenSandBoxInert - TokenAuditPolicy - TokenOrigin - TokenElevationType - TokenLinkedToken - TokenElevation - TokenHasRestrictions - TokenAccessInformation - TokenVirtualizationAllowed - TokenVirtualizationEnabled - TokenIntegrityLevel - TokenUIAccess - TokenMandatoryPolicy - TokenLogonSid - MaxTokenInfoClass -) - -type SIDAndAttributes struct { - Sid *SID - Attributes uint32 -} - -type Tokenuser struct { - User SIDAndAttributes -} - -type Tokenprimarygroup struct { - PrimaryGroup *SID -} - -type Tokengroups struct { - GroupCount uint32 - Groups [1]SIDAndAttributes -} - -//sys OpenProcessToken(h Handle, access uint32, token *Token) (err error) = advapi32.OpenProcessToken -//sys GetTokenInformation(t Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) = advapi32.GetTokenInformation -//sys GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) = userenv.GetUserProfileDirectoryW - -// An access token contains the security information for a logon session. -// The system creates an access token when a user logs on, and every -// process executed on behalf of the user has a copy of the token. -// The token identifies the user, the user's groups, and the user's -// privileges. The system uses the token to control access to securable -// objects and to control the ability of the user to perform various -// system-related operations on the local computer. -type Token Handle - -// OpenCurrentProcessToken opens the access token -// associated with current process. -func OpenCurrentProcessToken() (Token, error) { - p, e := GetCurrentProcess() - if e != nil { - return 0, e - } - var t Token - e = OpenProcessToken(p, TOKEN_QUERY, &t) - if e != nil { - return 0, e - } - return t, nil -} - -// Close releases access to access token. -func (t Token) Close() error { - return CloseHandle(Handle(t)) -} - -// getInfo retrieves a specified type of information about an access token. -func (t Token) getInfo(class uint32, initSize int) (unsafe.Pointer, error) { - n := uint32(initSize) - for { - b := make([]byte, n) - e := GetTokenInformation(t, class, &b[0], uint32(len(b)), &n) - if e == nil { - return unsafe.Pointer(&b[0]), nil - } - if e != ERROR_INSUFFICIENT_BUFFER { - return nil, e - } - if n <= uint32(len(b)) { - return nil, e - } - } -} - -// GetTokenUser retrieves access token t user account information. -func (t Token) GetTokenUser() (*Tokenuser, error) { - i, e := t.getInfo(TokenUser, 50) - if e != nil { - return nil, e - } - return (*Tokenuser)(i), nil -} - -// GetTokenGroups retrieves group accounts associated with access token t. -func (t Token) GetTokenGroups() (*Tokengroups, error) { - i, e := t.getInfo(TokenGroups, 50) - if e != nil { - return nil, e - } - return (*Tokengroups)(i), nil -} - -// GetTokenPrimaryGroup retrieves access token t primary group information. -// A pointer to a SID structure representing a group that will become -// the primary group of any objects created by a process using this access token. -func (t Token) GetTokenPrimaryGroup() (*Tokenprimarygroup, error) { - i, e := t.getInfo(TokenPrimaryGroup, 50) - if e != nil { - return nil, e - } - return (*Tokenprimarygroup)(i), nil -} - -// GetUserProfileDirectory retrieves path to the -// root directory of the access token t user's profile. -func (t Token) GetUserProfileDirectory() (string, error) { - n := uint32(100) - for { - b := make([]uint16, n) - e := GetUserProfileDirectory(t, &b[0], &n) - if e == nil { - return UTF16ToString(b), nil - } - if e != ERROR_INSUFFICIENT_BUFFER { - return "", e - } - if n <= uint32(len(b)) { - return "", e - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/service.go b/Godeps/_workspace/src/golang.org/x/sys/windows/service.go deleted file mode 100644 index 1c11d39..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/service.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package windows - -const ( - SC_MANAGER_CONNECT = 1 - SC_MANAGER_CREATE_SERVICE = 2 - SC_MANAGER_ENUMERATE_SERVICE = 4 - SC_MANAGER_LOCK = 8 - SC_MANAGER_QUERY_LOCK_STATUS = 16 - SC_MANAGER_MODIFY_BOOT_CONFIG = 32 - SC_MANAGER_ALL_ACCESS = 0xf003f -) - -//sys OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenSCManagerW - -const ( - SERVICE_KERNEL_DRIVER = 1 - SERVICE_FILE_SYSTEM_DRIVER = 2 - SERVICE_ADAPTER = 4 - SERVICE_RECOGNIZER_DRIVER = 8 - SERVICE_WIN32_OWN_PROCESS = 16 - SERVICE_WIN32_SHARE_PROCESS = 32 - SERVICE_WIN32 = SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS - SERVICE_INTERACTIVE_PROCESS = 256 - SERVICE_DRIVER = SERVICE_KERNEL_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_RECOGNIZER_DRIVER - SERVICE_TYPE_ALL = SERVICE_WIN32 | SERVICE_ADAPTER | SERVICE_DRIVER | SERVICE_INTERACTIVE_PROCESS - - SERVICE_BOOT_START = 0 - SERVICE_SYSTEM_START = 1 - SERVICE_AUTO_START = 2 - SERVICE_DEMAND_START = 3 - SERVICE_DISABLED = 4 - - SERVICE_ERROR_IGNORE = 0 - SERVICE_ERROR_NORMAL = 1 - SERVICE_ERROR_SEVERE = 2 - SERVICE_ERROR_CRITICAL = 3 - - SC_STATUS_PROCESS_INFO = 0 - - SERVICE_STOPPED = 1 - SERVICE_START_PENDING = 2 - SERVICE_STOP_PENDING = 3 - SERVICE_RUNNING = 4 - SERVICE_CONTINUE_PENDING = 5 - SERVICE_PAUSE_PENDING = 6 - SERVICE_PAUSED = 7 - SERVICE_NO_CHANGE = 0xffffffff - - SERVICE_ACCEPT_STOP = 1 - SERVICE_ACCEPT_PAUSE_CONTINUE = 2 - SERVICE_ACCEPT_SHUTDOWN = 4 - SERVICE_ACCEPT_PARAMCHANGE = 8 - SERVICE_ACCEPT_NETBINDCHANGE = 16 - SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 32 - SERVICE_ACCEPT_POWEREVENT = 64 - SERVICE_ACCEPT_SESSIONCHANGE = 128 - - SERVICE_CONTROL_STOP = 1 - SERVICE_CONTROL_PAUSE = 2 - SERVICE_CONTROL_CONTINUE = 3 - SERVICE_CONTROL_INTERROGATE = 4 - SERVICE_CONTROL_SHUTDOWN = 5 - SERVICE_CONTROL_PARAMCHANGE = 6 - SERVICE_CONTROL_NETBINDADD = 7 - SERVICE_CONTROL_NETBINDREMOVE = 8 - SERVICE_CONTROL_NETBINDENABLE = 9 - SERVICE_CONTROL_NETBINDDISABLE = 10 - SERVICE_CONTROL_DEVICEEVENT = 11 - SERVICE_CONTROL_HARDWAREPROFILECHANGE = 12 - SERVICE_CONTROL_POWEREVENT = 13 - SERVICE_CONTROL_SESSIONCHANGE = 14 - - SERVICE_ACTIVE = 1 - SERVICE_INACTIVE = 2 - SERVICE_STATE_ALL = 3 - - SERVICE_QUERY_CONFIG = 1 - SERVICE_CHANGE_CONFIG = 2 - SERVICE_QUERY_STATUS = 4 - SERVICE_ENUMERATE_DEPENDENTS = 8 - SERVICE_START = 16 - SERVICE_STOP = 32 - SERVICE_PAUSE_CONTINUE = 64 - SERVICE_INTERROGATE = 128 - SERVICE_USER_DEFINED_CONTROL = 256 - SERVICE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL - SERVICE_RUNS_IN_SYSTEM_PROCESS = 1 - SERVICE_CONFIG_DESCRIPTION = 1 - SERVICE_CONFIG_FAILURE_ACTIONS = 2 - - NO_ERROR = 0 -) - -type SERVICE_STATUS struct { - ServiceType uint32 - CurrentState uint32 - ControlsAccepted uint32 - Win32ExitCode uint32 - ServiceSpecificExitCode uint32 - CheckPoint uint32 - WaitHint uint32 -} - -type SERVICE_TABLE_ENTRY struct { - ServiceName *uint16 - ServiceProc uintptr -} - -type QUERY_SERVICE_CONFIG struct { - ServiceType uint32 - StartType uint32 - ErrorControl uint32 - BinaryPathName *uint16 - LoadOrderGroup *uint16 - TagId uint32 - Dependencies *uint16 - ServiceStartName *uint16 - DisplayName *uint16 -} - -type SERVICE_DESCRIPTION struct { - Description *uint16 -} - -//sys CloseServiceHandle(handle Handle) (err error) = advapi32.CloseServiceHandle -//sys CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access uint32, srvType uint32, startType uint32, errCtl uint32, pathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16) (handle Handle, err error) [failretval==0] = advapi32.CreateServiceW -//sys OpenService(mgr Handle, serviceName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenServiceW -//sys DeleteService(service Handle) (err error) = advapi32.DeleteService -//sys StartService(service Handle, numArgs uint32, argVectors **uint16) (err error) = advapi32.StartServiceW -//sys QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error) = advapi32.QueryServiceStatus -//sys ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err error) = advapi32.ControlService -//sys StartServiceCtrlDispatcher(serviceTable *SERVICE_TABLE_ENTRY) (err error) = advapi32.StartServiceCtrlDispatcherW -//sys SetServiceStatus(service Handle, serviceStatus *SERVICE_STATUS) (err error) = advapi32.SetServiceStatus -//sys ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, errorControl uint32, binaryPathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16, displayName *uint16) (err error) = advapi32.ChangeServiceConfigW -//sys QueryServiceConfig(service Handle, serviceConfig *QUERY_SERVICE_CONFIG, bufSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfigW -//sys ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error) = advapi32.ChangeServiceConfig2W -//sys QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfig2W diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/str.go b/Godeps/_workspace/src/golang.org/x/sys/windows/str.go deleted file mode 100644 index 917cc2a..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/str.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package windows - -func itoa(val int) string { // do it here rather than with fmt to avoid dependency - if val < 0 { - return "-" + itoa(-val) - } - var buf [32]byte // big enough for int64 - i := len(buf) - 1 - for val >= 10 { - buf[i] = byte(val%10 + '0') - i-- - val /= 10 - } - buf[i] = byte(val + '0') - return string(buf[i:]) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/debug/log.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/debug/log.go deleted file mode 100644 index e51ab42..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/debug/log.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package debug - -import ( - "os" - "strconv" -) - -// Log interface allows different log implementations to be used. -type Log interface { - Close() error - Info(eid uint32, msg string) error - Warning(eid uint32, msg string) error - Error(eid uint32, msg string) error -} - -// ConsoleLog provides access to the console. -type ConsoleLog struct { - Name string -} - -// New creates new ConsoleLog. -func New(source string) *ConsoleLog { - return &ConsoleLog{Name: source} -} - -// Close closes console log l. -func (l *ConsoleLog) Close() error { - return nil -} - -func (l *ConsoleLog) report(kind string, eid uint32, msg string) error { - s := l.Name + "." + kind + "(" + strconv.Itoa(int(eid)) + "): " + msg + "\n" - _, err := os.Stdout.Write([]byte(s)) - return err -} - -// Info writes an information event msg with event id eid to the console l. -func (l *ConsoleLog) Info(eid uint32, msg string) error { - return l.report("info", eid, msg) -} - -// Warning writes an warning event msg with event id eid to the console l. -func (l *ConsoleLog) Warning(eid uint32, msg string) error { - return l.report("warn", eid, msg) -} - -// Error writes an error event msg with event id eid to the console l. -func (l *ConsoleLog) Error(eid uint32, msg string) error { - return l.report("error", eid, msg) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/debug/service.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/debug/service.go deleted file mode 100644 index d5ab94b..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/debug/service.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -// Package debug provides facilities to execute svc.Handler on console. -// -package debug - -import ( - "os" - "os/signal" - "syscall" - - "golang.org/x/sys/windows/svc" -) - -// Run executes service name by calling appropriate handler function. -// The process is running on console, unlike real service. Use Ctrl+C to -// send "Stop" command to your service. -func Run(name string, handler svc.Handler) error { - cmds := make(chan svc.ChangeRequest) - changes := make(chan svc.Status) - - sig := make(chan os.Signal) - signal.Notify(sig) - - go func() { - status := svc.Status{State: svc.Stopped} - for { - select { - case <-sig: - cmds <- svc.ChangeRequest{svc.Stop, status} - case status = <-changes: - } - } - }() - - _, errno := handler.Execute([]string{name}, cmds, changes) - if errno != 0 { - return syscall.Errno(errno) - } - return nil -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/event.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/event.go deleted file mode 100644 index 0508e22..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/event.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package svc - -import ( - "errors" - - "golang.org/x/sys/windows" -) - -// event represents auto-reset, initially non-signaled Windows event. -// It is used to communicate between go and asm parts of this package. -type event struct { - h windows.Handle -} - -func newEvent() (*event, error) { - h, err := windows.CreateEvent(nil, 0, 0, nil) - if err != nil { - return nil, err - } - return &event{h: h}, nil -} - -func (e *event) Close() error { - return windows.CloseHandle(e.h) -} - -func (e *event) Set() error { - return windows.SetEvent(e.h) -} - -func (e *event) Wait() error { - s, err := windows.WaitForSingleObject(e.h, windows.INFINITE) - switch s { - case windows.WAIT_OBJECT_0: - break - case windows.WAIT_FAILED: - return err - default: - return errors.New("unexpected result from WaitForSingleObject") - } - return nil -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/eventlog/install.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/eventlog/install.go deleted file mode 100644 index c76a376..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/eventlog/install.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package eventlog - -import ( - "errors" - - "golang.org/x/sys/windows" - "golang.org/x/sys/windows/registry" -) - -const ( - // Log levels. - Info = windows.EVENTLOG_INFORMATION_TYPE - Warning = windows.EVENTLOG_WARNING_TYPE - Error = windows.EVENTLOG_ERROR_TYPE -) - -const addKeyName = `SYSTEM\CurrentControlSet\Services\EventLog\Application` - -// Install modifies PC registry to allow logging with an event source src. -// It adds all required keys and values to the event log registry key. -// Install uses msgFile as the event message file. If useExpandKey is true, -// the event message file is installed as REG_EXPAND_SZ value, -// otherwise as REG_SZ. Use bitwise of log.Error, log.Warning and -// log.Info to specify events supported by the new event source. -func Install(src, msgFile string, useExpandKey bool, eventsSupported uint32) error { - appkey, err := registry.OpenKey(registry.LOCAL_MACHINE, addKeyName, registry.CREATE_SUB_KEY) - if err != nil { - return err - } - defer appkey.Close() - - sk, alreadyExist, err := registry.CreateKey(appkey, src, registry.SET_VALUE) - if err != nil { - return err - } - defer sk.Close() - if alreadyExist { - return errors.New(addKeyName + `\` + src + " registry key already exists") - } - - err = sk.SetDWordValue("CustomSource", 1) - if err != nil { - return err - } - if useExpandKey { - err = sk.SetExpandStringValue("EventMessageFile", msgFile) - } else { - err = sk.SetStringValue("EventMessageFile", msgFile) - } - if err != nil { - return err - } - err = sk.SetDWordValue("TypesSupported", eventsSupported) - if err != nil { - return err - } - return nil -} - -// InstallAsEventCreate is the same as Install, but uses -// %SystemRoot%\System32\EventCreate.exe as the event message file. -func InstallAsEventCreate(src string, eventsSupported uint32) error { - return Install(src, "%SystemRoot%\\System32\\EventCreate.exe", true, eventsSupported) -} - -// Remove deletes all registry elements installed by the correspondent Install. -func Remove(src string) error { - appkey, err := registry.OpenKey(registry.LOCAL_MACHINE, addKeyName, registry.SET_VALUE) - if err != nil { - return err - } - defer appkey.Close() - return registry.DeleteKey(appkey, src) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/eventlog/log.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/eventlog/log.go deleted file mode 100644 index 46e5153..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/eventlog/log.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -// Package eventlog implements access to Windows event log. -// -package eventlog - -import ( - "errors" - "syscall" - - "golang.org/x/sys/windows" -) - -// Log provides access to the system log. -type Log struct { - Handle windows.Handle -} - -// Open retrieves a handle to the specified event log. -func Open(source string) (*Log, error) { - return OpenRemote("", source) -} - -// OpenRemote does the same as Open, but on different computer host. -func OpenRemote(host, source string) (*Log, error) { - if source == "" { - return nil, errors.New("Specify event log source") - } - var s *uint16 - if host != "" { - s = syscall.StringToUTF16Ptr(host) - } - h, err := windows.RegisterEventSource(s, syscall.StringToUTF16Ptr(source)) - if err != nil { - return nil, err - } - return &Log{Handle: h}, nil -} - -// Close closes event log l. -func (l *Log) Close() error { - return windows.DeregisterEventSource(l.Handle) -} - -func (l *Log) report(etype uint16, eid uint32, msg string) error { - ss := []*uint16{syscall.StringToUTF16Ptr(msg)} - return windows.ReportEvent(l.Handle, etype, 0, eid, 0, 1, 0, &ss[0], nil) -} - -// Info writes an information event msg with event id eid to the end of event log l. -// When EventCreate.exe is used, eid must be between 1 and 1000. -func (l *Log) Info(eid uint32, msg string) error { - return l.report(windows.EVENTLOG_INFORMATION_TYPE, eid, msg) -} - -// Warning writes an warning event msg with event id eid to the end of event log l. -// When EventCreate.exe is used, eid must be between 1 and 1000. -func (l *Log) Warning(eid uint32, msg string) error { - return l.report(windows.EVENTLOG_WARNING_TYPE, eid, msg) -} - -// Error writes an error event msg with event id eid to the end of event log l. -// When EventCreate.exe is used, eid must be between 1 and 1000. -func (l *Log) Error(eid uint32, msg string) error { - return l.report(windows.EVENTLOG_ERROR_TYPE, eid, msg) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/eventlog/log_test.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/eventlog/log_test.go deleted file mode 100644 index 4dd8ad9..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/eventlog/log_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package eventlog_test - -import ( - "testing" - - "golang.org/x/sys/windows/svc/eventlog" -) - -func TestLog(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode - it modifies system logs") - } - - const name = "mylog" - const supports = eventlog.Error | eventlog.Warning | eventlog.Info - err := eventlog.InstallAsEventCreate(name, supports) - if err != nil { - t.Fatalf("Install failed: %s", err) - } - defer func() { - err = eventlog.Remove(name) - if err != nil { - t.Fatalf("Remove failed: %s", err) - } - }() - - l, err := eventlog.Open(name) - if err != nil { - t.Fatalf("Open failed: %s", err) - } - defer l.Close() - - err = l.Info(1, "info") - if err != nil { - t.Fatalf("Info failed: %s", err) - } - err = l.Warning(2, "warning") - if err != nil { - t.Fatalf("Warning failed: %s", err) - } - err = l.Error(3, "error") - if err != nil { - t.Fatalf("Error failed: %s", err) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/beep.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/beep.go deleted file mode 100644 index dcf2340..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/beep.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package main - -import ( - "syscall" -) - -// BUG(brainman): MessageBeep Windows api is broken on Windows 7, -// so this example does not beep when runs as service on Windows 7. - -var ( - beepFunc = syscall.MustLoadDLL("user32.dll").MustFindProc("MessageBeep") -) - -func beep() { - beepFunc.Call(0xffffffff) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/install.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/install.go deleted file mode 100644 index 39cb00d..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/install.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package main - -import ( - "fmt" - "os" - "path/filepath" - - "golang.org/x/sys/windows/svc/eventlog" - "golang.org/x/sys/windows/svc/mgr" -) - -func exePath() (string, error) { - prog := os.Args[0] - p, err := filepath.Abs(prog) - if err != nil { - return "", err - } - fi, err := os.Stat(p) - if err == nil { - if !fi.Mode().IsDir() { - return p, nil - } - err = fmt.Errorf("%s is directory", p) - } - if filepath.Ext(p) == "" { - p += ".exe" - fi, err := os.Stat(p) - if err == nil { - if !fi.Mode().IsDir() { - return p, nil - } - err = fmt.Errorf("%s is directory", p) - } - } - return "", err -} - -func installService(name, desc string) error { - exepath, err := exePath() - if err != nil { - return err - } - m, err := mgr.Connect() - if err != nil { - return err - } - defer m.Disconnect() - s, err := m.OpenService(name) - if err == nil { - s.Close() - return fmt.Errorf("service %s already exists", name) - } - s, err = m.CreateService(name, exepath, mgr.Config{DisplayName: desc}, "is", "auto-started") - if err != nil { - return err - } - defer s.Close() - err = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info) - if err != nil { - s.Delete() - return fmt.Errorf("SetupEventLogSource() failed: %s", err) - } - return nil -} - -func removeService(name string) error { - m, err := mgr.Connect() - if err != nil { - return err - } - defer m.Disconnect() - s, err := m.OpenService(name) - if err != nil { - return fmt.Errorf("service %s is not installed", name) - } - defer s.Close() - err = s.Delete() - if err != nil { - return err - } - err = eventlog.Remove(name) - if err != nil { - return fmt.Errorf("RemoveEventLogSource() failed: %s", err) - } - return nil -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/main.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/main.go deleted file mode 100644 index dc96c08..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/main.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -// Example service program that beeps. -// -// The program demonstrates how to create Windows service and -// install / remove it on a computer. It also shows how to -// stop / start / pause / continue any service, and how to -// write to event log. It also shows how to use debug -// facilities available in debug package. -// -package main - -import ( - "fmt" - "log" - "os" - "strings" - - "golang.org/x/sys/windows/svc" -) - -func usage(errmsg string) { - fmt.Fprintf(os.Stderr, - "%s\n\n"+ - "usage: %s \n"+ - " where is one of\n"+ - " install, remove, debug, start, stop, pause or continue.\n", - errmsg, os.Args[0]) - os.Exit(2) -} - -func main() { - const svcName = "myservice" - - isIntSess, err := svc.IsAnInteractiveSession() - if err != nil { - log.Fatalf("failed to determine if we are running in an interactive session: %v", err) - } - if !isIntSess { - runService(svcName, false) - return - } - - if len(os.Args) < 2 { - usage("no command specified") - } - - cmd := strings.ToLower(os.Args[1]) - switch cmd { - case "debug": - runService(svcName, true) - return - case "install": - err = installService(svcName, "my service") - case "remove": - err = removeService(svcName) - case "start": - err = startService(svcName) - case "stop": - err = controlService(svcName, svc.Stop, svc.Stopped) - case "pause": - err = controlService(svcName, svc.Pause, svc.Paused) - case "continue": - err = controlService(svcName, svc.Continue, svc.Running) - default: - usage(fmt.Sprintf("invalid command %s", cmd)) - } - if err != nil { - log.Fatalf("failed to %s %s: %v", cmd, svcName, err) - } - return -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/manage.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/manage.go deleted file mode 100644 index 782dbd9..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/manage.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package main - -import ( - "fmt" - "time" - - "golang.org/x/sys/windows/svc" - "golang.org/x/sys/windows/svc/mgr" -) - -func startService(name string) error { - m, err := mgr.Connect() - if err != nil { - return err - } - defer m.Disconnect() - s, err := m.OpenService(name) - if err != nil { - return fmt.Errorf("could not access service: %v", err) - } - defer s.Close() - err = s.Start("is", "manual-started") - if err != nil { - return fmt.Errorf("could not start service: %v", err) - } - return nil -} - -func controlService(name string, c svc.Cmd, to svc.State) error { - m, err := mgr.Connect() - if err != nil { - return err - } - defer m.Disconnect() - s, err := m.OpenService(name) - if err != nil { - return fmt.Errorf("could not access service: %v", err) - } - defer s.Close() - status, err := s.Control(c) - if err != nil { - return fmt.Errorf("could not send control=%d: %v", c, err) - } - timeout := time.Now().Add(10 * time.Second) - for status.State != to { - if timeout.Before(time.Now()) { - return fmt.Errorf("timeout waiting for service to go to state=%d", to) - } - time.Sleep(300 * time.Millisecond) - status, err = s.Query() - if err != nil { - return fmt.Errorf("could not retrieve service status: %v", err) - } - } - return nil -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/service.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/service.go deleted file mode 100644 index 237e809..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/example/service.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package main - -import ( - "fmt" - "time" - - "golang.org/x/sys/windows/svc" - "golang.org/x/sys/windows/svc/debug" - "golang.org/x/sys/windows/svc/eventlog" -) - -var elog debug.Log - -type myservice struct{} - -func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) { - const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue - changes <- svc.Status{State: svc.StartPending} - fasttick := time.Tick(500 * time.Millisecond) - slowtick := time.Tick(2 * time.Second) - tick := fasttick - changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} -loop: - for { - select { - case <-tick: - beep() - elog.Info(1, "beep") - case c := <-r: - switch c.Cmd { - case svc.Interrogate: - changes <- c.CurrentStatus - // Testing deadlock from https://code.google.com/p/winsvc/issues/detail?id=4 - time.Sleep(100 * time.Millisecond) - changes <- c.CurrentStatus - case svc.Stop, svc.Shutdown: - break loop - case svc.Pause: - changes <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted} - tick = slowtick - case svc.Continue: - changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} - tick = fasttick - default: - elog.Error(1, fmt.Sprintf("unexpected control request #%d", c)) - } - } - } - changes <- svc.Status{State: svc.StopPending} - return -} - -func runService(name string, isDebug bool) { - var err error - if isDebug { - elog = debug.New(name) - } else { - elog, err = eventlog.Open(name) - if err != nil { - return - } - } - defer elog.Close() - - elog.Info(1, fmt.Sprintf("starting %s service", name)) - run := svc.Run - if isDebug { - run = debug.Run - } - err = run(name, &myservice{}) - if err != nil { - elog.Error(1, fmt.Sprintf("%s service failed: %v", name, err)) - return - } - elog.Info(1, fmt.Sprintf("%s service stopped", name)) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/go12.c b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/go12.c deleted file mode 100644 index 6f1be1f..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/go12.c +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows -// +build !go1.3 - -// copied from pkg/runtime -typedef unsigned int uint32; -typedef unsigned long long int uint64; -#ifdef _64BIT -typedef uint64 uintptr; -#else -typedef uint32 uintptr; -#endif - -// from sys_386.s or sys_amd64.s -void ·servicemain(void); - -void -·getServiceMain(uintptr *r) -{ - *r = (uintptr)·servicemain; -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/go12.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/go12.go deleted file mode 100644 index 6f0a924..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/go12.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows -// +build !go1.3 - -package svc - -// from go12.c -func getServiceMain(r *uintptr) diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/go13.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/go13.go deleted file mode 100644 index 432a9e7..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/go13.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows -// +build go1.3 - -package svc - -import "unsafe" - -const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const - -// Should be a built-in for unsafe.Pointer? -func add(p unsafe.Pointer, x uintptr) unsafe.Pointer { - return unsafe.Pointer(uintptr(p) + x) -} - -// funcPC returns the entry PC of the function f. -// It assumes that f is a func value. Otherwise the behavior is undefined. -func funcPC(f interface{}) uintptr { - return **(**uintptr)(add(unsafe.Pointer(&f), ptrSize)) -} - -// from sys_386.s and sys_amd64.s -func servicectlhandler(ctl uint32) uintptr -func servicemain(argc uint32, argv **uint16) - -func getServiceMain(r *uintptr) { - *r = funcPC(servicemain) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/config.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/config.go deleted file mode 100644 index 0a6edba..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/config.go +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package mgr - -import ( - "syscall" - "unicode/utf16" - "unsafe" - - "golang.org/x/sys/windows" -) - -const ( - // Service start types. - StartManual = windows.SERVICE_DEMAND_START // the service must be started manually - StartAutomatic = windows.SERVICE_AUTO_START // the service will start by itself whenever the computer reboots - StartDisabled = windows.SERVICE_DISABLED // the service cannot be started - - // The severity of the error, and action taken, - // if this service fails to start. - ErrorCritical = windows.SERVICE_ERROR_CRITICAL - ErrorIgnore = windows.SERVICE_ERROR_IGNORE - ErrorNormal = windows.SERVICE_ERROR_NORMAL - ErrorSevere = windows.SERVICE_ERROR_SEVERE -) - -// TODO(brainman): Password is not returned by windows.QueryServiceConfig, not sure how to get it. - -type Config struct { - ServiceType uint32 - StartType uint32 - ErrorControl uint32 - BinaryPathName string // fully qualified path to the service binary file, can also include arguments for an auto-start service - LoadOrderGroup string - TagId uint32 - Dependencies []string - ServiceStartName string // name of the account under which the service should run - DisplayName string - Password string - Description string -} - -func toString(p *uint16) string { - if p == nil { - return "" - } - return syscall.UTF16ToString((*[4096]uint16)(unsafe.Pointer(p))[:]) -} - -func toStringSlice(ps *uint16) []string { - if ps == nil { - return nil - } - r := make([]string, 0) - for from, i, p := 0, 0, (*[1 << 24]uint16)(unsafe.Pointer(ps)); true; i++ { - if p[i] == 0 { - // empty string marks the end - if i <= from { - break - } - r = append(r, string(utf16.Decode(p[from:i]))) - from = i + 1 - } - } - return r -} - -// Config retrieves service s configuration paramteres. -func (s *Service) Config() (Config, error) { - var p *windows.QUERY_SERVICE_CONFIG - n := uint32(1024) - for { - b := make([]byte, n) - p = (*windows.QUERY_SERVICE_CONFIG)(unsafe.Pointer(&b[0])) - err := windows.QueryServiceConfig(s.Handle, p, n, &n) - if err == nil { - break - } - if err.(syscall.Errno) != syscall.ERROR_INSUFFICIENT_BUFFER { - return Config{}, err - } - if n <= uint32(len(b)) { - return Config{}, err - } - } - - var p2 *windows.SERVICE_DESCRIPTION - n = uint32(1024) - for { - b := make([]byte, n) - p2 = (*windows.SERVICE_DESCRIPTION)(unsafe.Pointer(&b[0])) - err := windows.QueryServiceConfig2(s.Handle, - windows.SERVICE_CONFIG_DESCRIPTION, &b[0], n, &n) - if err == nil { - break - } - if err.(syscall.Errno) != syscall.ERROR_INSUFFICIENT_BUFFER { - return Config{}, err - } - if n <= uint32(len(b)) { - return Config{}, err - } - } - - return Config{ - ServiceType: p.ServiceType, - StartType: p.StartType, - ErrorControl: p.ErrorControl, - BinaryPathName: toString(p.BinaryPathName), - LoadOrderGroup: toString(p.LoadOrderGroup), - TagId: p.TagId, - Dependencies: toStringSlice(p.Dependencies), - ServiceStartName: toString(p.ServiceStartName), - DisplayName: toString(p.DisplayName), - Description: toString(p2.Description), - }, nil -} - -func updateDescription(handle windows.Handle, desc string) error { - d := windows.SERVICE_DESCRIPTION{toPtr(desc)} - return windows.ChangeServiceConfig2(handle, - windows.SERVICE_CONFIG_DESCRIPTION, (*byte)(unsafe.Pointer(&d))) -} - -// UpdateConfig updates service s configuration parameters. -func (s *Service) UpdateConfig(c Config) error { - err := windows.ChangeServiceConfig(s.Handle, c.ServiceType, c.StartType, - c.ErrorControl, toPtr(c.BinaryPathName), toPtr(c.LoadOrderGroup), - nil, toStringBlock(c.Dependencies), toPtr(c.ServiceStartName), - toPtr(c.Password), toPtr(c.DisplayName)) - if err != nil { - return err - } - return updateDescription(s.Handle, c.Description) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/mgr.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/mgr.go deleted file mode 100644 index 4d7e72e..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/mgr.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -// Package mgr can be used to manage Windows service programs. -// It can be used to install and remove them. It can also start, -// stop and pause them. The package can query / change current -// service state and config parameters. -// -package mgr - -import ( - "syscall" - "unicode/utf16" - - "golang.org/x/sys/windows" -) - -// Mgr is used to manage Windows service. -type Mgr struct { - Handle windows.Handle -} - -// Connect establishes a connection to the service control manager. -func Connect() (*Mgr, error) { - return ConnectRemote("") -} - -// ConnectRemote establishes a connection to the -// service control manager on computer named host. -func ConnectRemote(host string) (*Mgr, error) { - var s *uint16 - if host != "" { - s = syscall.StringToUTF16Ptr(host) - } - h, err := windows.OpenSCManager(s, nil, windows.SC_MANAGER_ALL_ACCESS) - if err != nil { - return nil, err - } - return &Mgr{Handle: h}, nil -} - -// Disconnect closes connection to the service control manager m. -func (m *Mgr) Disconnect() error { - return windows.CloseServiceHandle(m.Handle) -} - -func toPtr(s string) *uint16 { - if len(s) == 0 { - return nil - } - return syscall.StringToUTF16Ptr(s) -} - -// toStringBlock terminates strings in ss with 0, and then -// concatenates them together. It also adds extra 0 at the end. -func toStringBlock(ss []string) *uint16 { - if len(ss) == 0 { - return nil - } - t := "" - for _, s := range ss { - if s != "" { - t += s + "\x00" - } - } - if t == "" { - return nil - } - t += "\x00" - return &utf16.Encode([]rune(t))[0] -} - -// CreateService installs new service name on the system. -// The service will be executed by running exepath binary. -// Use config c to specify service parameters. -// If service StartType is set to StartAutomatic, -// args will be passed to svc.Handle.Execute. -func (m *Mgr) CreateService(name, exepath string, c Config, args ...string) (*Service, error) { - if c.StartType == 0 { - c.StartType = StartManual - } - if c.ErrorControl == 0 { - c.ErrorControl = ErrorNormal - } - s := syscall.EscapeArg(exepath) - for _, v := range args { - s += " " + syscall.EscapeArg(v) - } - h, err := windows.CreateService(m.Handle, toPtr(name), toPtr(c.DisplayName), - windows.SERVICE_ALL_ACCESS, windows.SERVICE_WIN32_OWN_PROCESS, - c.StartType, c.ErrorControl, toPtr(s), toPtr(c.LoadOrderGroup), - nil, toStringBlock(c.Dependencies), toPtr(c.ServiceStartName), toPtr(c.Password)) - if err != nil { - return nil, err - } - if c.Description != "" { - err = updateDescription(h, c.Description) - if err != nil { - return nil, err - } - } - return &Service{Name: name, Handle: h}, nil -} - -// OpenService retrieves access to service name, so it can -// be interrogated and controlled. -func (m *Mgr) OpenService(name string) (*Service, error) { - h, err := windows.OpenService(m.Handle, syscall.StringToUTF16Ptr(name), windows.SERVICE_ALL_ACCESS) - if err != nil { - return nil, err - } - return &Service{Name: name, Handle: h}, nil -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/mgr_test.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/mgr_test.go deleted file mode 100644 index deb9fac..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/mgr_test.go +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package mgr_test - -import ( - "os" - "path/filepath" - "sort" - "strings" - "testing" - "time" - - "golang.org/x/sys/windows/svc/mgr" -) - -func TestOpenLanManServer(t *testing.T) { - m, err := mgr.Connect() - if err != nil { - t.Fatalf("SCM connection failed: %s", err) - } - defer m.Disconnect() - - s, err := m.OpenService("LanmanServer") - if err != nil { - t.Fatalf("OpenService(lanmanserver) failed: %s", err) - } - defer s.Close() - - _, err = s.Config() - if err != nil { - t.Fatalf("Config failed: %s", err) - } -} - -func install(t *testing.T, m *mgr.Mgr, name, exepath string, c mgr.Config) { - // Sometimes it takes a while for the service to get - // removed after previous test run. - for i := 0; ; i++ { - s, err := m.OpenService(name) - if err != nil { - break - } - s.Close() - - if i > 10 { - t.Fatalf("service %s already exists", name) - } - time.Sleep(300 * time.Millisecond) - } - - s, err := m.CreateService(name, exepath, c) - if err != nil { - t.Fatalf("CreateService(%s) failed: %v", name, err) - } - defer s.Close() -} - -func depString(d []string) string { - if len(d) == 0 { - return "" - } - for i := range d { - d[i] = strings.ToLower(d[i]) - } - ss := sort.StringSlice(d) - ss.Sort() - return strings.Join([]string(ss), " ") -} - -func testConfig(t *testing.T, s *mgr.Service, should mgr.Config) mgr.Config { - is, err := s.Config() - if err != nil { - t.Fatalf("Config failed: %s", err) - } - if should.DisplayName != is.DisplayName { - t.Fatalf("config mismatch: DisplayName is %q, but should have %q", is.DisplayName, should.DisplayName) - } - if should.StartType != is.StartType { - t.Fatalf("config mismatch: StartType is %v, but should have %v", is.StartType, should.StartType) - } - if should.Description != is.Description { - t.Fatalf("config mismatch: Description is %q, but should have %q", is.Description, should.Description) - } - if depString(should.Dependencies) != depString(is.Dependencies) { - t.Fatalf("config mismatch: Dependencies is %v, but should have %v", is.Dependencies, should.Dependencies) - } - return is -} - -func remove(t *testing.T, s *mgr.Service) { - err := s.Delete() - if err != nil { - t.Fatalf("Delete failed: %s", err) - } -} - -func TestMyService(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode - it modifies system services") - } - - const name = "myservice" - - m, err := mgr.Connect() - if err != nil { - t.Fatalf("SCM connection failed: %s", err) - } - defer m.Disconnect() - - c := mgr.Config{ - StartType: mgr.StartDisabled, - DisplayName: "my service", - Description: "my service is just a test", - Dependencies: []string{"LanmanServer", "W32Time"}, - } - - exename := os.Args[0] - exepath, err := filepath.Abs(exename) - if err != nil { - t.Fatalf("filepath.Abs(%s) failed: %s", exename, err) - } - - install(t, m, name, exepath, c) - - s, err := m.OpenService(name) - if err != nil { - t.Fatalf("service %s is not installed", name) - } - defer s.Close() - - c.BinaryPathName = exepath - c = testConfig(t, s, c) - - c.StartType = mgr.StartManual - err = s.UpdateConfig(c) - if err != nil { - t.Fatalf("UpdateConfig failed: %v", err) - } - - testConfig(t, s, c) - - remove(t, s) -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/service.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/service.go deleted file mode 100644 index 465f3c3..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/mgr/service.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package mgr - -import ( - "syscall" - - "golang.org/x/sys/windows" - "golang.org/x/sys/windows/svc" -) - -// TODO(brainman): Use EnumDependentServices to enumerate dependent services. - -// TODO(brainman): Use EnumServicesStatus to enumerate services in the specified service control manager database. - -// Service is used to access Windows service. -type Service struct { - Name string - Handle windows.Handle -} - -// Delete marks service s for deletion from the service control manager database. -func (s *Service) Delete() error { - return windows.DeleteService(s.Handle) -} - -// Close relinquish access to the service s. -func (s *Service) Close() error { - return windows.CloseServiceHandle(s.Handle) -} - -// Start starts service s. -// args will be passed to svc.Handler.Execute. -func (s *Service) Start(args ...string) error { - var p **uint16 - if len(args) > 0 { - vs := make([]*uint16, len(args)) - for i, _ := range vs { - vs[i] = syscall.StringToUTF16Ptr(args[i]) - } - p = &vs[0] - } - return windows.StartService(s.Handle, uint32(len(args)), p) -} - -// Control sends state change request c to the servce s. -func (s *Service) Control(c svc.Cmd) (svc.Status, error) { - var t windows.SERVICE_STATUS - err := windows.ControlService(s.Handle, uint32(c), &t) - if err != nil { - return svc.Status{}, err - } - return svc.Status{ - State: svc.State(t.CurrentState), - Accepts: svc.Accepted(t.ControlsAccepted), - }, nil -} - -// Query returns current status of service s. -func (s *Service) Query() (svc.Status, error) { - var t windows.SERVICE_STATUS - err := windows.QueryServiceStatus(s.Handle, &t) - if err != nil { - return svc.Status{}, err - } - return svc.Status{ - State: svc.State(t.CurrentState), - Accepts: svc.Accepted(t.ControlsAccepted), - }, nil -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/security.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/security.go deleted file mode 100644 index 6fbc923..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/security.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package svc - -import ( - "unsafe" - - "golang.org/x/sys/windows" -) - -func allocSid(subAuth0 uint32) (*windows.SID, error) { - var sid *windows.SID - err := windows.AllocateAndInitializeSid(&windows.SECURITY_NT_AUTHORITY, - 1, subAuth0, 0, 0, 0, 0, 0, 0, 0, &sid) - if err != nil { - return nil, err - } - return sid, nil -} - -// IsAnInteractiveSession determines if calling process is running interactively. -// It queries the process token for membership in the Interactive group. -// http://stackoverflow.com/questions/2668851/how-do-i-detect-that-my-application-is-running-as-service-or-in-an-interactive-s -func IsAnInteractiveSession() (bool, error) { - interSid, err := allocSid(windows.SECURITY_INTERACTIVE_RID) - if err != nil { - return false, err - } - defer windows.FreeSid(interSid) - - serviceSid, err := allocSid(windows.SECURITY_SERVICE_RID) - if err != nil { - return false, err - } - defer windows.FreeSid(serviceSid) - - t, err := windows.OpenCurrentProcessToken() - if err != nil { - return false, err - } - defer t.Close() - - gs, err := t.GetTokenGroups() - if err != nil { - return false, err - } - p := unsafe.Pointer(&gs.Groups[0]) - groups := (*[2 << 20]windows.SIDAndAttributes)(p)[:gs.GroupCount] - for _, g := range groups { - if windows.EqualSid(g.Sid, interSid) { - return true, nil - } - if windows.EqualSid(g.Sid, serviceSid) { - return false, nil - } - } - return false, nil -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/service.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/service.go deleted file mode 100644 index 9864f7a..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/service.go +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -// Package svc provides everything required to build Windows service. -// -package svc - -import ( - "errors" - "runtime" - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -// State describes service execution state (Stopped, Running and so on). -type State uint32 - -const ( - Stopped = State(windows.SERVICE_STOPPED) - StartPending = State(windows.SERVICE_START_PENDING) - StopPending = State(windows.SERVICE_STOP_PENDING) - Running = State(windows.SERVICE_RUNNING) - ContinuePending = State(windows.SERVICE_CONTINUE_PENDING) - PausePending = State(windows.SERVICE_PAUSE_PENDING) - Paused = State(windows.SERVICE_PAUSED) -) - -// Cmd represents service state change request. It is sent to a service -// by the service manager, and should be actioned upon by the service. -type Cmd uint32 - -const ( - Stop = Cmd(windows.SERVICE_CONTROL_STOP) - Pause = Cmd(windows.SERVICE_CONTROL_PAUSE) - Continue = Cmd(windows.SERVICE_CONTROL_CONTINUE) - Interrogate = Cmd(windows.SERVICE_CONTROL_INTERROGATE) - Shutdown = Cmd(windows.SERVICE_CONTROL_SHUTDOWN) -) - -// Accepted is used to describe commands accepted by the service. -// Note that Interrogate is always accepted. -type Accepted uint32 - -const ( - AcceptStop = Accepted(windows.SERVICE_ACCEPT_STOP) - AcceptShutdown = Accepted(windows.SERVICE_ACCEPT_SHUTDOWN) - AcceptPauseAndContinue = Accepted(windows.SERVICE_ACCEPT_PAUSE_CONTINUE) -) - -// Status combines State and Accepted commands to fully describe running service. -type Status struct { - State State - Accepts Accepted - CheckPoint uint32 // used to report progress during a lengthy operation - WaitHint uint32 // estimated time required for a pending operation, in milliseconds -} - -// ChangeRequest is sent to the service Handler to request service status change. -type ChangeRequest struct { - Cmd Cmd - CurrentStatus Status -} - -// Handler is the interface that must be implemented to build Windows service. -type Handler interface { - - // Execute will be called by the package code at the start of - // the service, and the service will exit once Execute completes. - // Inside Execute you must read service change requests from r and - // act accordingly. You must keep service control manager up to date - // about state of your service by writing into s as required. - // args contains service name followed by argument strings passed - // to the service. - // You can provide service exit code in exitCode return parameter, - // with 0 being "no error". You can also indicate if exit code, - // if any, is service specific or not by using svcSpecificEC - // parameter. - Execute(args []string, r <-chan ChangeRequest, s chan<- Status) (svcSpecificEC bool, exitCode uint32) -} - -var ( - // These are used by asm code. - goWaitsH uintptr - cWaitsH uintptr - ssHandle uintptr - sName *uint16 - sArgc uintptr - sArgv **uint16 - ctlHandlerProc uintptr - cSetEvent uintptr - cWaitForSingleObject uintptr - cRegisterServiceCtrlHandlerW uintptr -) - -func init() { - k := syscall.MustLoadDLL("kernel32.dll") - cSetEvent = k.MustFindProc("SetEvent").Addr() - cWaitForSingleObject = k.MustFindProc("WaitForSingleObject").Addr() - a := syscall.MustLoadDLL("advapi32.dll") - cRegisterServiceCtrlHandlerW = a.MustFindProc("RegisterServiceCtrlHandlerW").Addr() -} - -type ctlEvent struct { - cmd Cmd - errno uint32 -} - -// service provides access to windows service api. -type service struct { - name string - h windows.Handle - cWaits *event - goWaits *event - c chan ctlEvent - handler Handler -} - -func newService(name string, handler Handler) (*service, error) { - var s service - var err error - s.name = name - s.c = make(chan ctlEvent) - s.handler = handler - s.cWaits, err = newEvent() - if err != nil { - return nil, err - } - s.goWaits, err = newEvent() - if err != nil { - s.cWaits.Close() - return nil, err - } - return &s, nil -} - -func (s *service) close() error { - s.cWaits.Close() - s.goWaits.Close() - return nil -} - -type exitCode struct { - isSvcSpecific bool - errno uint32 -} - -func (s *service) updateStatus(status *Status, ec *exitCode) error { - if s.h == 0 { - return errors.New("updateStatus with no service status handle") - } - var t windows.SERVICE_STATUS - t.ServiceType = windows.SERVICE_WIN32_OWN_PROCESS - t.CurrentState = uint32(status.State) - if status.Accepts&AcceptStop != 0 { - t.ControlsAccepted |= windows.SERVICE_ACCEPT_STOP - } - if status.Accepts&AcceptShutdown != 0 { - t.ControlsAccepted |= windows.SERVICE_ACCEPT_SHUTDOWN - } - if status.Accepts&AcceptPauseAndContinue != 0 { - t.ControlsAccepted |= windows.SERVICE_ACCEPT_PAUSE_CONTINUE - } - if ec.errno == 0 { - t.Win32ExitCode = windows.NO_ERROR - t.ServiceSpecificExitCode = windows.NO_ERROR - } else if ec.isSvcSpecific { - t.Win32ExitCode = uint32(windows.ERROR_SERVICE_SPECIFIC_ERROR) - t.ServiceSpecificExitCode = ec.errno - } else { - t.Win32ExitCode = ec.errno - t.ServiceSpecificExitCode = windows.NO_ERROR - } - t.CheckPoint = status.CheckPoint - t.WaitHint = status.WaitHint - return windows.SetServiceStatus(s.h, &t) -} - -const ( - sysErrSetServiceStatusFailed = uint32(syscall.APPLICATION_ERROR) + iota - sysErrNewThreadInCallback -) - -func (s *service) run() { - s.goWaits.Wait() - s.h = windows.Handle(ssHandle) - argv := (*[100]*int16)(unsafe.Pointer(sArgv))[:sArgc] - args := make([]string, len(argv)) - for i, a := range argv { - args[i] = syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(a))[:]) - } - - cmdsToHandler := make(chan ChangeRequest) - changesFromHandler := make(chan Status) - exitFromHandler := make(chan exitCode) - - go func() { - ss, errno := s.handler.Execute(args, cmdsToHandler, changesFromHandler) - exitFromHandler <- exitCode{ss, errno} - }() - - status := Status{State: Stopped} - ec := exitCode{isSvcSpecific: true, errno: 0} - var outch chan ChangeRequest - inch := s.c - var cmd Cmd -loop: - for { - select { - case r := <-inch: - if r.errno != 0 { - ec.errno = r.errno - break loop - } - inch = nil - outch = cmdsToHandler - cmd = r.cmd - case outch <- ChangeRequest{cmd, status}: - inch = s.c - outch = nil - case c := <-changesFromHandler: - err := s.updateStatus(&c, &ec) - if err != nil { - // best suitable error number - ec.errno = sysErrSetServiceStatusFailed - if err2, ok := err.(syscall.Errno); ok { - ec.errno = uint32(err2) - } - break loop - } - status = c - case ec = <-exitFromHandler: - break loop - } - } - - s.updateStatus(&Status{State: Stopped}, &ec) - s.cWaits.Set() -} - -func newCallback(fn interface{}) (cb uintptr, err error) { - defer func() { - r := recover() - if r == nil { - return - } - cb = 0 - switch v := r.(type) { - case string: - err = errors.New(v) - case error: - err = v - default: - err = errors.New("unexpected panic in syscall.NewCallback") - } - }() - return syscall.NewCallback(fn), nil -} - -// BUG(brainman): There is no mechanism to run multiple services -// inside one single executable. Perhaps, it can be overcome by -// using RegisterServiceCtrlHandlerEx Windows api. - -// Run executes service name by calling appropriate handler function. -func Run(name string, handler Handler) error { - runtime.LockOSThread() - - tid := windows.GetCurrentThreadId() - - s, err := newService(name, handler) - if err != nil { - return err - } - - ctlHandler := func(ctl uint32) uintptr { - e := ctlEvent{cmd: Cmd(ctl)} - // We assume that this callback function is running on - // the same thread as Run. Nowhere in MS documentation - // I could find statement to guarantee that. So putting - // check here to verify, otherwise things will go bad - // quickly, if ignored. - i := windows.GetCurrentThreadId() - if i != tid { - e.errno = sysErrNewThreadInCallback - } - s.c <- e - return 0 - } - - var svcmain uintptr - getServiceMain(&svcmain) - t := []windows.SERVICE_TABLE_ENTRY{ - {syscall.StringToUTF16Ptr(s.name), svcmain}, - {nil, 0}, - } - - goWaitsH = uintptr(s.goWaits.h) - cWaitsH = uintptr(s.cWaits.h) - sName = t[0].ServiceName - ctlHandlerProc, err = newCallback(ctlHandler) - if err != nil { - return err - } - - go s.run() - - err = windows.StartServiceCtrlDispatcher(&t[0]) - if err != nil { - return err - } - return nil -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/svc_test.go b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/svc_test.go deleted file mode 100644 index 764da54..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/svc_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package svc_test - -import ( - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "testing" - "time" - - "golang.org/x/sys/windows/svc" - "golang.org/x/sys/windows/svc/mgr" -) - -func getState(t *testing.T, s *mgr.Service) svc.State { - status, err := s.Query() - if err != nil { - t.Fatalf("Query(%s) failed: %s", s.Name, err) - } - return status.State -} - -func testState(t *testing.T, s *mgr.Service, want svc.State) { - have := getState(t, s) - if have != want { - t.Fatalf("%s state is=%d want=%d", s.Name, have, want) - } -} - -func waitState(t *testing.T, s *mgr.Service, want svc.State) { - for i := 0; ; i++ { - have := getState(t, s) - if have == want { - return - } - if i > 10 { - t.Fatalf("%s state is=%d, waiting timeout", s.Name, have) - } - time.Sleep(300 * time.Millisecond) - } -} - -func TestExample(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode - it modifies system services") - } - - const name = "myservice" - - m, err := mgr.Connect() - if err != nil { - t.Fatalf("SCM connection failed: %s", err) - } - defer m.Disconnect() - - dir, err := ioutil.TempDir("", "svc") - if err != nil { - t.Fatalf("failed to create temp directory: %v", err) - } - defer os.RemoveAll(dir) - - exepath := filepath.Join(dir, "a.exe") - o, err := exec.Command("go", "build", "-o", exepath, "golang.org/x/sys/windows/svc/example").CombinedOutput() - if err != nil { - t.Fatalf("failed to build service program: %v\n%v", err, string(o)) - } - - s, err := m.OpenService(name) - if err == nil { - err = s.Delete() - if err != nil { - s.Close() - t.Fatalf("Delete failed: %s", err) - } - s.Close() - } - s, err = m.CreateService(name, exepath, mgr.Config{DisplayName: "my service"}, "is", "auto-started") - if err != nil { - t.Fatalf("CreateService(%s) failed: %v", name, err) - } - defer s.Close() - - testState(t, s, svc.Stopped) - err = s.Start("is", "manual-started") - if err != nil { - t.Fatalf("Start(%s) failed: %s", s.Name, err) - } - waitState(t, s, svc.Running) - time.Sleep(1 * time.Second) - - // testing deadlock from issues 4. - _, err = s.Control(svc.Interrogate) - if err != nil { - t.Fatalf("Control(%s) failed: %s", s.Name, err) - } - _, err = s.Control(svc.Interrogate) - if err != nil { - t.Fatalf("Control(%s) failed: %s", s.Name, err) - } - time.Sleep(1 * time.Second) - - _, err = s.Control(svc.Stop) - if err != nil { - t.Fatalf("Control(%s) failed: %s", s.Name, err) - } - waitState(t, s, svc.Stopped) - - err = s.Delete() - if err != nil { - t.Fatalf("Delete failed: %s", err) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/sys_386.s b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/sys_386.s deleted file mode 100644 index 5e11bfa..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/sys_386.s +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -// func servicemain(argc uint32, argv **uint16) -TEXT ·servicemain(SB),7,$0 - MOVL argc+0(FP), AX - MOVL AX, ·sArgc(SB) - MOVL argv+4(FP), AX - MOVL AX, ·sArgv(SB) - - PUSHL BP - PUSHL BX - PUSHL SI - PUSHL DI - - SUBL $12, SP - - MOVL ·sName(SB), AX - MOVL AX, (SP) - MOVL $·servicectlhandler(SB), AX - MOVL AX, 4(SP) - MOVL ·cRegisterServiceCtrlHandlerW(SB), AX - MOVL SP, BP - CALL AX - MOVL BP, SP - CMPL AX, $0 - JE exit - MOVL AX, ·ssHandle(SB) - - MOVL ·goWaitsH(SB), AX - MOVL AX, (SP) - MOVL ·cSetEvent(SB), AX - MOVL SP, BP - CALL AX - MOVL BP, SP - - MOVL ·cWaitsH(SB), AX - MOVL AX, (SP) - MOVL $-1, AX - MOVL AX, 4(SP) - MOVL ·cWaitForSingleObject(SB), AX - MOVL SP, BP - CALL AX - MOVL BP, SP - -exit: - ADDL $12, SP - - POPL DI - POPL SI - POPL BX - POPL BP - - MOVL 0(SP), CX - ADDL $12, SP - JMP CX - -// I do not know why, but this seems to be the only way to call -// ctlHandlerProc on Windows 7. - -// func servicectlhandler(ctl uint32) uintptr -TEXT ·servicectlhandler(SB),7,$0 - MOVL ·ctlHandlerProc(SB), CX - JMP CX diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/sys_amd64.s b/Godeps/_workspace/src/golang.org/x/sys/windows/svc/sys_amd64.s deleted file mode 100644 index 87dbec8..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/svc/sys_amd64.s +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -// func servicemain(argc uint32, argv **uint16) -TEXT ·servicemain(SB),7,$0 - MOVL CX, ·sArgc(SB) - MOVL DX, ·sArgv(SB) - - SUBQ $32, SP // stack for the first 4 syscall params - - MOVQ ·sName(SB), CX - MOVQ $·servicectlhandler(SB), DX - MOVQ ·cRegisterServiceCtrlHandlerW(SB), AX - CALL AX - CMPQ AX, $0 - JE exit - MOVQ AX, ·ssHandle(SB) - - MOVQ ·goWaitsH(SB), CX - MOVQ ·cSetEvent(SB), AX - CALL AX - - MOVQ ·cWaitsH(SB), CX - MOVQ $4294967295, DX - MOVQ ·cWaitForSingleObject(SB), AX - CALL AX - -exit: - ADDQ $32, SP - RET - -// I do not know why, but this seems to be the only way to call -// ctlHandlerProc on Windows 7. - -// func servicectlhandler(ctl uint32) uintptr -TEXT ·servicectlhandler(SB),7,$0 - MOVQ ·ctlHandlerProc(SB), AX - JMP AX diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/syscall.go b/Godeps/_workspace/src/golang.org/x/sys/windows/syscall.go deleted file mode 100644 index 281cd66..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/syscall.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -// Package windows contains an interface to the low-level operating system -// primitives. OS details vary depending on the underlying system, and -// by default, godoc will display the OS-specific documentation for the current -// system. If you want godoc to display syscall documentation for another -// system, set $GOOS and $GOARCH to the desired system. For example, if -// you want to view documentation for freebsd/arm on linux/amd64, set $GOOS -// to freebsd and $GOARCH to arm. -// The primary use of this package is inside other packages that provide a more -// portable interface to the system, such as "os", "time" and "net". Use -// those packages rather than this one if you can. -// For details of the functions and data types in this package consult -// the manuals for the appropriate operating system. -// These calls return err == nil to indicate success; otherwise -// err represents an operating system error describing the failure and -// holds a value of type syscall.Errno. -package windows - -import ( - "syscall" - "unsafe" -) - -// ByteSliceFromString returns a NUL-terminated slice of bytes -// containing the text of s. If s contains a NUL byte at any -// location, it returns (nil, syscall.EINVAL). -func ByteSliceFromString(s string) ([]byte, error) { - for i := 0; i < len(s); i++ { - if s[i] == 0 { - return nil, syscall.EINVAL - } - } - a := make([]byte, len(s)+1) - copy(a, s) - return a, nil -} - -// BytePtrFromString returns a pointer to a NUL-terminated array of -// bytes containing the text of s. If s contains a NUL byte at any -// location, it returns (nil, syscall.EINVAL). -func BytePtrFromString(s string) (*byte, error) { - a, err := ByteSliceFromString(s) - if err != nil { - return nil, err - } - return &a[0], nil -} - -// Single-word zero for use when we need a valid pointer to 0 bytes. -// See mksyscall.pl. -var _zero uintptr - -func (ts *Timespec) Unix() (sec int64, nsec int64) { - return int64(ts.Sec), int64(ts.Nsec) -} - -func (tv *Timeval) Unix() (sec int64, nsec int64) { - return int64(tv.Sec), int64(tv.Usec) * 1000 -} - -func (ts *Timespec) Nano() int64 { - return int64(ts.Sec)*1e9 + int64(ts.Nsec) -} - -func (tv *Timeval) Nano() int64 { - return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000 -} - -// use is a no-op, but the compiler cannot see that it is. -// Calling use(p) ensures that p is kept live until that point. -//go:noescape -func use(p unsafe.Pointer) diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/syscall_test.go b/Godeps/_workspace/src/golang.org/x/sys/windows/syscall_test.go deleted file mode 100644 index 62588b9..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/syscall_test.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package windows_test - -import ( - "testing" - - "golang.org/x/sys/windows" -) - -func testSetGetenv(t *testing.T, key, value string) { - err := windows.Setenv(key, value) - if err != nil { - t.Fatalf("Setenv failed to set %q: %v", value, err) - } - newvalue, found := windows.Getenv(key) - if !found { - t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) - } - if newvalue != value { - t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) - } -} - -func TestEnv(t *testing.T) { - testSetGetenv(t, "TESTENV", "AVALUE") - // make sure TESTENV gets set to "", not deleted - testSetGetenv(t, "TESTENV", "") -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/syscall_windows.go b/Godeps/_workspace/src/golang.org/x/sys/windows/syscall_windows.go deleted file mode 100644 index c798402..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/syscall_windows.go +++ /dev/null @@ -1,986 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Windows system calls. - -package windows - -import ( - errorspkg "errors" - "sync" - "syscall" - "unicode/utf16" - "unsafe" -) - -//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go eventlog.go service.go syscall_windows.go security_windows.go - -type Handle uintptr - -const InvalidHandle = ^Handle(0) - -// StringToUTF16 is deprecated. Use UTF16FromString instead. -// If s contains a NUL byte this function panics instead of -// returning an error. -func StringToUTF16(s string) []uint16 { - a, err := UTF16FromString(s) - if err != nil { - panic("windows: string with NUL passed to StringToUTF16") - } - return a -} - -// UTF16FromString returns the UTF-16 encoding of the UTF-8 string -// s, with a terminating NUL added. If s contains a NUL byte at any -// location, it returns (nil, syscall.EINVAL). -func UTF16FromString(s string) ([]uint16, error) { - for i := 0; i < len(s); i++ { - if s[i] == 0 { - return nil, syscall.EINVAL - } - } - return utf16.Encode([]rune(s + "\x00")), nil -} - -// UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s, -// with a terminating NUL removed. -func UTF16ToString(s []uint16) string { - for i, v := range s { - if v == 0 { - s = s[0:i] - break - } - } - return string(utf16.Decode(s)) -} - -// StringToUTF16Ptr is deprecated. Use UTF16PtrFromString instead. -// If s contains a NUL byte this function panics instead of -// returning an error. -func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] } - -// UTF16PtrFromString returns pointer to the UTF-16 encoding of -// the UTF-8 string s, with a terminating NUL added. If s -// contains a NUL byte at any location, it returns (nil, syscall.EINVAL). -func UTF16PtrFromString(s string) (*uint16, error) { - a, err := UTF16FromString(s) - if err != nil { - return nil, err - } - return &a[0], nil -} - -func Getpagesize() int { return 4096 } - -// Converts a Go function to a function pointer conforming -// to the stdcall or cdecl calling convention. This is useful when -// interoperating with Windows code requiring callbacks. -// Implemented in runtime/syscall_windows.goc -func NewCallback(fn interface{}) uintptr -func NewCallbackCDecl(fn interface{}) uintptr - -// windows api calls - -//sys GetLastError() (lasterr error) -//sys LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW -//sys FreeLibrary(handle Handle) (err error) -//sys GetProcAddress(module Handle, procname string) (proc uintptr, err error) -//sys GetVersion() (ver uint32, err error) -//sys FormatMessage(flags uint32, msgsrc uint32, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW -//sys ExitProcess(exitcode uint32) -//sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile int32) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW -//sys ReadFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) -//sys WriteFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) -//sys SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff] -//sys CloseHandle(handle Handle) (err error) -//sys GetStdHandle(stdhandle int) (handle Handle, err error) [failretval==InvalidHandle] -//sys findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW -//sys findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW -//sys FindClose(handle Handle) (err error) -//sys GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error) -//sys GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW -//sys SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW -//sys CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW -//sys RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW -//sys DeleteFile(path *uint16) (err error) = DeleteFileW -//sys MoveFile(from *uint16, to *uint16) (err error) = MoveFileW -//sys GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW -//sys GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW -//sys SetEndOfFile(handle Handle) (err error) -//sys GetSystemTimeAsFileTime(time *Filetime) -//sys GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff] -//sys CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uint32, threadcnt uint32) (handle Handle, err error) -//sys GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uint32, overlapped **Overlapped, timeout uint32) (err error) -//sys PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uint32, overlapped *Overlapped) (err error) -//sys CancelIo(s Handle) (err error) -//sys CancelIoEx(s Handle, o *Overlapped) (err error) -//sys CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = CreateProcessW -//sys OpenProcess(da uint32, inheritHandle bool, pid uint32) (handle Handle, err error) -//sys TerminateProcess(handle Handle, exitcode uint32) (err error) -//sys GetExitCodeProcess(handle Handle, exitcode *uint32) (err error) -//sys GetStartupInfo(startupInfo *StartupInfo) (err error) = GetStartupInfoW -//sys GetCurrentProcess() (pseudoHandle Handle, err error) -//sys GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error) -//sys DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error) -//sys WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff] -//sys GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPathW -//sys CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error) -//sys GetFileType(filehandle Handle) (n uint32, err error) -//sys CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) = advapi32.CryptAcquireContextW -//sys CryptReleaseContext(provhandle Handle, flags uint32) (err error) = advapi32.CryptReleaseContext -//sys CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) = advapi32.CryptGenRandom -//sys GetEnvironmentStrings() (envs *uint16, err error) [failretval==nil] = kernel32.GetEnvironmentStringsW -//sys FreeEnvironmentStrings(envs *uint16) (err error) = kernel32.FreeEnvironmentStringsW -//sys GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) = kernel32.GetEnvironmentVariableW -//sys SetEnvironmentVariable(name *uint16, value *uint16) (err error) = kernel32.SetEnvironmentVariableW -//sys SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) -//sys GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW -//sys SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW -//sys GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW -//sys GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW -//sys CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW -//sys LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0] -//sys SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error) -//sys FlushFileBuffers(handle Handle) (err error) -//sys GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) = kernel32.GetFullPathNameW -//sys GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) = kernel32.GetLongPathNameW -//sys GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) = kernel32.GetShortPathNameW -//sys CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) = kernel32.CreateFileMappingW -//sys MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error) -//sys UnmapViewOfFile(addr uintptr) (err error) -//sys FlushViewOfFile(addr uintptr, length uintptr) (err error) -//sys VirtualLock(addr uintptr, length uintptr) (err error) -//sys VirtualUnlock(addr uintptr, length uintptr) (err error) -//sys TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) = mswsock.TransmitFile -//sys ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) = kernel32.ReadDirectoryChangesW -//sys CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) = crypt32.CertOpenSystemStoreW -//sys CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) [failretval==InvalidHandle] = crypt32.CertOpenStore -//sys CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) [failretval==nil] = crypt32.CertEnumCertificatesInStore -//sys CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) = crypt32.CertAddCertificateContextToStore -//sys CertCloseStore(store Handle, flags uint32) (err error) = crypt32.CertCloseStore -//sys CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) = crypt32.CertGetCertificateChain -//sys CertFreeCertificateChain(ctx *CertChainContext) = crypt32.CertFreeCertificateChain -//sys CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) [failretval==nil] = crypt32.CertCreateCertificateContext -//sys CertFreeCertificateContext(ctx *CertContext) (err error) = crypt32.CertFreeCertificateContext -//sys CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) = crypt32.CertVerifyCertificateChainPolicy -//sys RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) = advapi32.RegOpenKeyExW -//sys RegCloseKey(key Handle) (regerrno error) = advapi32.RegCloseKey -//sys RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegQueryInfoKeyW -//sys RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegEnumKeyExW -//sys RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegQueryValueExW -//sys getCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId -//sys GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode -//sys WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW -//sys ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW -//sys CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot -//sys Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32FirstW -//sys Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32NextW -//sys DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error) -// This function returns 1 byte BOOLEAN rather than the 4 byte BOOL. -//sys CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW -//sys CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW -//sys GetCurrentThreadId() (id uint32) -//sys CreateEvent(eventAttrs *syscall.SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) = kernel32.CreateEventW -//sys SetEvent(event Handle) (err error) = kernel32.SetEvent - -// syscall interface implementation for other packages - -func Exit(code int) { ExitProcess(uint32(code)) } - -func makeInheritSa() *SecurityAttributes { - var sa SecurityAttributes - sa.Length = uint32(unsafe.Sizeof(sa)) - sa.InheritHandle = 1 - return &sa -} - -func Open(path string, mode int, perm uint32) (fd Handle, err error) { - if len(path) == 0 { - return InvalidHandle, ERROR_FILE_NOT_FOUND - } - pathp, err := UTF16PtrFromString(path) - if err != nil { - return InvalidHandle, err - } - var access uint32 - switch mode & (O_RDONLY | O_WRONLY | O_RDWR) { - case O_RDONLY: - access = GENERIC_READ - case O_WRONLY: - access = GENERIC_WRITE - case O_RDWR: - access = GENERIC_READ | GENERIC_WRITE - } - if mode&O_CREAT != 0 { - access |= GENERIC_WRITE - } - if mode&O_APPEND != 0 { - access &^= GENERIC_WRITE - access |= FILE_APPEND_DATA - } - sharemode := uint32(FILE_SHARE_READ | FILE_SHARE_WRITE) - var sa *SecurityAttributes - if mode&O_CLOEXEC == 0 { - sa = makeInheritSa() - } - var createmode uint32 - switch { - case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL): - createmode = CREATE_NEW - case mode&(O_CREAT|O_TRUNC) == (O_CREAT | O_TRUNC): - createmode = CREATE_ALWAYS - case mode&O_CREAT == O_CREAT: - createmode = OPEN_ALWAYS - case mode&O_TRUNC == O_TRUNC: - createmode = TRUNCATE_EXISTING - default: - createmode = OPEN_EXISTING - } - h, e := CreateFile(pathp, access, sharemode, sa, createmode, FILE_ATTRIBUTE_NORMAL, 0) - return h, e -} - -func Read(fd Handle, p []byte) (n int, err error) { - var done uint32 - e := ReadFile(fd, p, &done, nil) - if e != nil { - if e == ERROR_BROKEN_PIPE { - // NOTE(brainman): work around ERROR_BROKEN_PIPE is returned on reading EOF from stdin - return 0, nil - } - return 0, e - } - if raceenabled { - if done > 0 { - raceWriteRange(unsafe.Pointer(&p[0]), int(done)) - } - raceAcquire(unsafe.Pointer(&ioSync)) - } - return int(done), nil -} - -func Write(fd Handle, p []byte) (n int, err error) { - if raceenabled { - raceReleaseMerge(unsafe.Pointer(&ioSync)) - } - var done uint32 - e := WriteFile(fd, p, &done, nil) - if e != nil { - return 0, e - } - if raceenabled && done > 0 { - raceReadRange(unsafe.Pointer(&p[0]), int(done)) - } - return int(done), nil -} - -var ioSync int64 - -func Seek(fd Handle, offset int64, whence int) (newoffset int64, err error) { - var w uint32 - switch whence { - case 0: - w = FILE_BEGIN - case 1: - w = FILE_CURRENT - case 2: - w = FILE_END - } - hi := int32(offset >> 32) - lo := int32(offset) - // use GetFileType to check pipe, pipe can't do seek - ft, _ := GetFileType(fd) - if ft == FILE_TYPE_PIPE { - return 0, syscall.EPIPE - } - rlo, e := SetFilePointer(fd, lo, &hi, w) - if e != nil { - return 0, e - } - return int64(hi)<<32 + int64(rlo), nil -} - -func Close(fd Handle) (err error) { - return CloseHandle(fd) -} - -var ( - Stdin = getStdHandle(STD_INPUT_HANDLE) - Stdout = getStdHandle(STD_OUTPUT_HANDLE) - Stderr = getStdHandle(STD_ERROR_HANDLE) -) - -func getStdHandle(h int) (fd Handle) { - r, _ := GetStdHandle(h) - CloseOnExec(r) - return r -} - -const ImplementsGetwd = true - -func Getwd() (wd string, err error) { - b := make([]uint16, 300) - n, e := GetCurrentDirectory(uint32(len(b)), &b[0]) - if e != nil { - return "", e - } - return string(utf16.Decode(b[0:n])), nil -} - -func Chdir(path string) (err error) { - pathp, err := UTF16PtrFromString(path) - if err != nil { - return err - } - return SetCurrentDirectory(pathp) -} - -func Mkdir(path string, mode uint32) (err error) { - pathp, err := UTF16PtrFromString(path) - if err != nil { - return err - } - return CreateDirectory(pathp, nil) -} - -func Rmdir(path string) (err error) { - pathp, err := UTF16PtrFromString(path) - if err != nil { - return err - } - return RemoveDirectory(pathp) -} - -func Unlink(path string) (err error) { - pathp, err := UTF16PtrFromString(path) - if err != nil { - return err - } - return DeleteFile(pathp) -} - -func Rename(oldpath, newpath string) (err error) { - from, err := UTF16PtrFromString(oldpath) - if err != nil { - return err - } - to, err := UTF16PtrFromString(newpath) - if err != nil { - return err - } - return MoveFile(from, to) -} - -func ComputerName() (name string, err error) { - var n uint32 = MAX_COMPUTERNAME_LENGTH + 1 - b := make([]uint16, n) - e := GetComputerName(&b[0], &n) - if e != nil { - return "", e - } - return string(utf16.Decode(b[0:n])), nil -} - -func Ftruncate(fd Handle, length int64) (err error) { - curoffset, e := Seek(fd, 0, 1) - if e != nil { - return e - } - defer Seek(fd, curoffset, 0) - _, e = Seek(fd, length, 0) - if e != nil { - return e - } - e = SetEndOfFile(fd) - if e != nil { - return e - } - return nil -} - -func Gettimeofday(tv *Timeval) (err error) { - var ft Filetime - GetSystemTimeAsFileTime(&ft) - *tv = NsecToTimeval(ft.Nanoseconds()) - return nil -} - -func Pipe(p []Handle) (err error) { - if len(p) != 2 { - return syscall.EINVAL - } - var r, w Handle - e := CreatePipe(&r, &w, makeInheritSa(), 0) - if e != nil { - return e - } - p[0] = r - p[1] = w - return nil -} - -func Utimes(path string, tv []Timeval) (err error) { - if len(tv) != 2 { - return syscall.EINVAL - } - pathp, e := UTF16PtrFromString(path) - if e != nil { - return e - } - h, e := CreateFile(pathp, - FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil, - OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0) - if e != nil { - return e - } - defer Close(h) - a := NsecToFiletime(tv[0].Nanoseconds()) - w := NsecToFiletime(tv[1].Nanoseconds()) - return SetFileTime(h, nil, &a, &w) -} - -func UtimesNano(path string, ts []Timespec) (err error) { - if len(ts) != 2 { - return syscall.EINVAL - } - pathp, e := UTF16PtrFromString(path) - if e != nil { - return e - } - h, e := CreateFile(pathp, - FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil, - OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0) - if e != nil { - return e - } - defer Close(h) - a := NsecToFiletime(TimespecToNsec(ts[0])) - w := NsecToFiletime(TimespecToNsec(ts[1])) - return SetFileTime(h, nil, &a, &w) -} - -func Fsync(fd Handle) (err error) { - return FlushFileBuffers(fd) -} - -func Chmod(path string, mode uint32) (err error) { - if mode == 0 { - return syscall.EINVAL - } - p, e := UTF16PtrFromString(path) - if e != nil { - return e - } - attrs, e := GetFileAttributes(p) - if e != nil { - return e - } - if mode&S_IWRITE != 0 { - attrs &^= FILE_ATTRIBUTE_READONLY - } else { - attrs |= FILE_ATTRIBUTE_READONLY - } - return SetFileAttributes(p, attrs) -} - -func LoadCancelIoEx() error { - return procCancelIoEx.Find() -} - -func LoadSetFileCompletionNotificationModes() error { - return procSetFileCompletionNotificationModes.Find() -} - -// net api calls - -const socket_error = uintptr(^uint32(0)) - -//sys WSAStartup(verreq uint32, data *WSAData) (sockerr error) = ws2_32.WSAStartup -//sys WSACleanup() (err error) [failretval==socket_error] = ws2_32.WSACleanup -//sys WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) [failretval==socket_error] = ws2_32.WSAIoctl -//sys socket(af int32, typ int32, protocol int32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.socket -//sys Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) [failretval==socket_error] = ws2_32.setsockopt -//sys Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockopt -//sys bind(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.bind -//sys connect(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.connect -//sys getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockname -//sys getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getpeername -//sys listen(s Handle, backlog int32) (err error) [failretval==socket_error] = ws2_32.listen -//sys shutdown(s Handle, how int32) (err error) [failretval==socket_error] = ws2_32.shutdown -//sys Closesocket(s Handle) (err error) [failretval==socket_error] = ws2_32.closesocket -//sys AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) = mswsock.AcceptEx -//sys GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) = mswsock.GetAcceptExSockaddrs -//sys WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecv -//sys WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASend -//sys WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecvFrom -//sys WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASendTo -//sys GetHostByName(name string) (h *Hostent, err error) [failretval==nil] = ws2_32.gethostbyname -//sys GetServByName(name string, proto string) (s *Servent, err error) [failretval==nil] = ws2_32.getservbyname -//sys Ntohs(netshort uint16) (u uint16) = ws2_32.ntohs -//sys GetProtoByName(name string) (p *Protoent, err error) [failretval==nil] = ws2_32.getprotobyname -//sys DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) = dnsapi.DnsQuery_W -//sys DnsRecordListFree(rl *DNSRecord, freetype uint32) = dnsapi.DnsRecordListFree -//sys DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) = dnsapi.DnsNameCompare_W -//sys GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) = ws2_32.GetAddrInfoW -//sys FreeAddrInfoW(addrinfo *AddrinfoW) = ws2_32.FreeAddrInfoW -//sys GetIfEntry(pIfRow *MibIfRow) (errcode error) = iphlpapi.GetIfEntry -//sys GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) = iphlpapi.GetAdaptersInfo -//sys SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) = kernel32.SetFileCompletionNotificationModes -//sys WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) [failretval==-1] = ws2_32.WSAEnumProtocolsW - -// For testing: clients can set this flag to force -// creation of IPv6 sockets to return EAFNOSUPPORT. -var SocketDisableIPv6 bool - -type RawSockaddrInet4 struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]uint8 -} - -type RawSockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddr struct { - Family uint16 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [96]int8 -} - -type Sockaddr interface { - sockaddr() (ptr unsafe.Pointer, len int32, err error) // lowercase; only we can define Sockaddrs -} - -type SockaddrInet4 struct { - Port int - Addr [4]byte - raw RawSockaddrInet4 -} - -func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, int32, error) { - if sa.Port < 0 || sa.Port > 0xFFFF { - return nil, 0, syscall.EINVAL - } - sa.raw.Family = AF_INET - p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) - p[0] = byte(sa.Port >> 8) - p[1] = byte(sa.Port) - for i := 0; i < len(sa.Addr); i++ { - sa.raw.Addr[i] = sa.Addr[i] - } - return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil -} - -type SockaddrInet6 struct { - Port int - ZoneId uint32 - Addr [16]byte - raw RawSockaddrInet6 -} - -func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, int32, error) { - if sa.Port < 0 || sa.Port > 0xFFFF { - return nil, 0, syscall.EINVAL - } - sa.raw.Family = AF_INET6 - p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) - p[0] = byte(sa.Port >> 8) - p[1] = byte(sa.Port) - sa.raw.Scope_id = sa.ZoneId - for i := 0; i < len(sa.Addr); i++ { - sa.raw.Addr[i] = sa.Addr[i] - } - return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil -} - -type SockaddrUnix struct { - Name string -} - -func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) { - // TODO(brainman): implement SockaddrUnix.sockaddr() - return nil, 0, syscall.EWINDOWS -} - -func (rsa *RawSockaddrAny) Sockaddr() (Sockaddr, error) { - switch rsa.Addr.Family { - case AF_UNIX: - return nil, syscall.EWINDOWS - - case AF_INET: - pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) - sa := new(SockaddrInet4) - p := (*[2]byte)(unsafe.Pointer(&pp.Port)) - sa.Port = int(p[0])<<8 + int(p[1]) - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] - } - return sa, nil - - case AF_INET6: - pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) - sa := new(SockaddrInet6) - p := (*[2]byte)(unsafe.Pointer(&pp.Port)) - sa.Port = int(p[0])<<8 + int(p[1]) - sa.ZoneId = pp.Scope_id - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] - } - return sa, nil - } - return nil, syscall.EAFNOSUPPORT -} - -func Socket(domain, typ, proto int) (fd Handle, err error) { - if domain == AF_INET6 && SocketDisableIPv6 { - return InvalidHandle, syscall.EAFNOSUPPORT - } - return socket(int32(domain), int32(typ), int32(proto)) -} - -func SetsockoptInt(fd Handle, level, opt int, value int) (err error) { - v := int32(value) - return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), int32(unsafe.Sizeof(v))) -} - -func Bind(fd Handle, sa Sockaddr) (err error) { - ptr, n, err := sa.sockaddr() - if err != nil { - return err - } - return bind(fd, ptr, n) -} - -func Connect(fd Handle, sa Sockaddr) (err error) { - ptr, n, err := sa.sockaddr() - if err != nil { - return err - } - return connect(fd, ptr, n) -} - -func Getsockname(fd Handle) (sa Sockaddr, err error) { - var rsa RawSockaddrAny - l := int32(unsafe.Sizeof(rsa)) - if err = getsockname(fd, &rsa, &l); err != nil { - return - } - return rsa.Sockaddr() -} - -func Getpeername(fd Handle) (sa Sockaddr, err error) { - var rsa RawSockaddrAny - l := int32(unsafe.Sizeof(rsa)) - if err = getpeername(fd, &rsa, &l); err != nil { - return - } - return rsa.Sockaddr() -} - -func Listen(s Handle, n int) (err error) { - return listen(s, int32(n)) -} - -func Shutdown(fd Handle, how int) (err error) { - return shutdown(fd, int32(how)) -} - -func WSASendto(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to Sockaddr, overlapped *Overlapped, croutine *byte) (err error) { - rsa, l, err := to.sockaddr() - if err != nil { - return err - } - return WSASendTo(s, bufs, bufcnt, sent, flags, (*RawSockaddrAny)(unsafe.Pointer(rsa)), l, overlapped, croutine) -} - -func LoadGetAddrInfo() error { - return procGetAddrInfoW.Find() -} - -var connectExFunc struct { - once sync.Once - addr uintptr - err error -} - -func LoadConnectEx() error { - connectExFunc.once.Do(func() { - var s Handle - s, connectExFunc.err = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) - if connectExFunc.err != nil { - return - } - defer CloseHandle(s) - var n uint32 - connectExFunc.err = WSAIoctl(s, - SIO_GET_EXTENSION_FUNCTION_POINTER, - (*byte)(unsafe.Pointer(&WSAID_CONNECTEX)), - uint32(unsafe.Sizeof(WSAID_CONNECTEX)), - (*byte)(unsafe.Pointer(&connectExFunc.addr)), - uint32(unsafe.Sizeof(connectExFunc.addr)), - &n, nil, 0) - }) - return connectExFunc.err -} - -func connectEx(s Handle, name unsafe.Pointer, namelen int32, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) (err error) { - r1, _, e1 := syscall.Syscall9(connectExFunc.addr, 7, uintptr(s), uintptr(name), uintptr(namelen), uintptr(unsafe.Pointer(sendBuf)), uintptr(sendDataLen), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func ConnectEx(fd Handle, sa Sockaddr, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) error { - err := LoadConnectEx() - if err != nil { - return errorspkg.New("failed to find ConnectEx: " + err.Error()) - } - ptr, n, err := sa.sockaddr() - if err != nil { - return err - } - return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped) -} - -// Invented structures to support what package os expects. -type Rusage struct { - CreationTime Filetime - ExitTime Filetime - KernelTime Filetime - UserTime Filetime -} - -type WaitStatus struct { - ExitCode uint32 -} - -func (w WaitStatus) Exited() bool { return true } - -func (w WaitStatus) ExitStatus() int { return int(w.ExitCode) } - -func (w WaitStatus) Signal() Signal { return -1 } - -func (w WaitStatus) CoreDump() bool { return false } - -func (w WaitStatus) Stopped() bool { return false } - -func (w WaitStatus) Continued() bool { return false } - -func (w WaitStatus) StopSignal() Signal { return -1 } - -func (w WaitStatus) Signaled() bool { return false } - -func (w WaitStatus) TrapCause() int { return -1 } - -// Timespec is an invented structure on Windows, but here for -// consistency with the corresponding package for other operating systems. -type Timespec struct { - Sec int64 - Nsec int64 -} - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = nsec / 1e9 - ts.Nsec = nsec % 1e9 - return -} - -// TODO(brainman): fix all needed for net - -func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error) { return 0, nil, syscall.EWINDOWS } -func Recvfrom(fd Handle, p []byte, flags int) (n int, from Sockaddr, err error) { - return 0, nil, syscall.EWINDOWS -} -func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error) { return syscall.EWINDOWS } -func SetsockoptTimeval(fd Handle, level, opt int, tv *Timeval) (err error) { return syscall.EWINDOWS } - -// The Linger struct is wrong but we only noticed after Go 1. -// sysLinger is the real system call structure. - -// BUG(brainman): The definition of Linger is not appropriate for direct use -// with Setsockopt and Getsockopt. -// Use SetsockoptLinger instead. - -type Linger struct { - Onoff int32 - Linger int32 -} - -type sysLinger struct { - Onoff uint16 - Linger uint16 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -func GetsockoptInt(fd Handle, level, opt int) (int, error) { return -1, syscall.EWINDOWS } - -func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) { - sys := sysLinger{Onoff: uint16(l.Onoff), Linger: uint16(l.Linger)} - return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&sys)), int32(unsafe.Sizeof(sys))) -} - -func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) { - return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4) -} -func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) { - return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq))) -} -func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) { - return syscall.EWINDOWS -} - -func Getpid() (pid int) { return int(getCurrentProcessId()) } - -func FindFirstFile(name *uint16, data *Win32finddata) (handle Handle, err error) { - // NOTE(rsc): The Win32finddata struct is wrong for the system call: - // the two paths are each one uint16 short. Use the correct struct, - // a win32finddata1, and then copy the results out. - // There is no loss of expressivity here, because the final - // uint16, if it is used, is supposed to be a NUL, and Go doesn't need that. - // For Go 1.1, we might avoid the allocation of win32finddata1 here - // by adding a final Bug [2]uint16 field to the struct and then - // adjusting the fields in the result directly. - var data1 win32finddata1 - handle, err = findFirstFile1(name, &data1) - if err == nil { - copyFindData(data, &data1) - } - return -} - -func FindNextFile(handle Handle, data *Win32finddata) (err error) { - var data1 win32finddata1 - err = findNextFile1(handle, &data1) - if err == nil { - copyFindData(data, &data1) - } - return -} - -func getProcessEntry(pid int) (*ProcessEntry32, error) { - snapshot, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) - if err != nil { - return nil, err - } - defer CloseHandle(snapshot) - var procEntry ProcessEntry32 - procEntry.Size = uint32(unsafe.Sizeof(procEntry)) - if err = Process32First(snapshot, &procEntry); err != nil { - return nil, err - } - for { - if procEntry.ProcessID == uint32(pid) { - return &procEntry, nil - } - err = Process32Next(snapshot, &procEntry) - if err != nil { - return nil, err - } - } -} - -func Getppid() (ppid int) { - pe, err := getProcessEntry(Getpid()) - if err != nil { - return -1 - } - return int(pe.ParentProcessID) -} - -// TODO(brainman): fix all needed for os -func Fchdir(fd Handle) (err error) { return syscall.EWINDOWS } -func Link(oldpath, newpath string) (err error) { return syscall.EWINDOWS } -func Symlink(path, link string) (err error) { return syscall.EWINDOWS } - -func Fchmod(fd Handle, mode uint32) (err error) { return syscall.EWINDOWS } -func Chown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS } -func Lchown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS } -func Fchown(fd Handle, uid int, gid int) (err error) { return syscall.EWINDOWS } - -func Getuid() (uid int) { return -1 } -func Geteuid() (euid int) { return -1 } -func Getgid() (gid int) { return -1 } -func Getegid() (egid int) { return -1 } -func Getgroups() (gids []int, err error) { return nil, syscall.EWINDOWS } - -type Signal int - -func (s Signal) Signal() {} - -func (s Signal) String() string { - if 0 <= s && int(s) < len(signals) { - str := signals[s] - if str != "" { - return str - } - } - return "signal " + itoa(int(s)) -} - -func LoadCreateSymbolicLink() error { - return procCreateSymbolicLinkW.Find() -} - -// Readlink returns the destination of the named symbolic link. -func Readlink(path string, buf []byte) (n int, err error) { - fd, err := CreateFile(StringToUTF16Ptr(path), GENERIC_READ, 0, nil, OPEN_EXISTING, - FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS, 0) - if err != nil { - return -1, err - } - defer CloseHandle(fd) - - rdbbuf := make([]byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE) - var bytesReturned uint32 - err = DeviceIoControl(fd, FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil) - if err != nil { - return -1, err - } - - rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0])) - var s string - switch rdb.ReparseTag { - case IO_REPARSE_TAG_SYMLINK: - data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer)) - p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0])) - s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2]) - case IO_REPARSE_TAG_MOUNT_POINT: - data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer)) - p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0])) - s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2]) - default: - // the path is not a symlink or junction but another type of reparse - // point - return -1, syscall.ENOENT - } - n = copy(buf, []byte(s)) - - return n, nil -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/syscall_windows_test.go b/Godeps/_workspace/src/golang.org/x/sys/windows/syscall_windows_test.go deleted file mode 100644 index 0462bcf..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/syscall_windows_test.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package windows_test - -import ( - "io/ioutil" - "os" - "path/filepath" - "syscall" - "testing" - - "golang.org/x/sys/windows" -) - -func TestWin32finddata(t *testing.T) { - dir, err := ioutil.TempDir("", "go-build") - if err != nil { - t.Fatalf("failed to create temp directory: %v", err) - } - defer os.RemoveAll(dir) - - path := filepath.Join(dir, "long_name.and_extension") - f, err := os.Create(path) - if err != nil { - t.Fatalf("failed to create %v: %v", path, err) - } - f.Close() - - type X struct { - fd windows.Win32finddata - got byte - pad [10]byte // to protect ourselves - - } - var want byte = 2 // it is unlikely to have this character in the filename - x := X{got: want} - - pathp, _ := windows.UTF16PtrFromString(path) - h, err := windows.FindFirstFile(pathp, &(x.fd)) - if err != nil { - t.Fatalf("FindFirstFile failed: %v", err) - } - err = windows.FindClose(h) - if err != nil { - t.Fatalf("FindClose failed: %v", err) - } - - if x.got != want { - t.Fatalf("memory corruption: want=%d got=%d", want, x.got) - } -} - -func abort(funcname string, err error) { - panic(funcname + " failed: " + err.Error()) -} - -func ExampleLoadLibrary() { - h, err := windows.LoadLibrary("kernel32.dll") - if err != nil { - abort("LoadLibrary", err) - } - defer windows.FreeLibrary(h) - proc, err := windows.GetProcAddress(h, "GetVersion") - if err != nil { - abort("GetProcAddress", err) - } - r, _, _ := syscall.Syscall(uintptr(proc), 0, 0, 0, 0) - major := byte(r) - minor := uint8(r >> 8) - build := uint16(r >> 16) - print("windows version ", major, ".", minor, " (Build ", build, ")\n") -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/zsyscall_windows.go b/Godeps/_workspace/src/golang.org/x/sys/windows/zsyscall_windows.go deleted file mode 100644 index cec5d5a..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/zsyscall_windows.go +++ /dev/null @@ -1,2177 +0,0 @@ -// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT - -package windows - -import "unsafe" -import "syscall" - -var _ unsafe.Pointer - -var ( - modadvapi32 = syscall.NewLazyDLL("advapi32.dll") - modkernel32 = syscall.NewLazyDLL("kernel32.dll") - modshell32 = syscall.NewLazyDLL("shell32.dll") - modmswsock = syscall.NewLazyDLL("mswsock.dll") - modcrypt32 = syscall.NewLazyDLL("crypt32.dll") - modws2_32 = syscall.NewLazyDLL("ws2_32.dll") - moddnsapi = syscall.NewLazyDLL("dnsapi.dll") - modiphlpapi = syscall.NewLazyDLL("iphlpapi.dll") - modsecur32 = syscall.NewLazyDLL("secur32.dll") - modnetapi32 = syscall.NewLazyDLL("netapi32.dll") - moduserenv = syscall.NewLazyDLL("userenv.dll") - - procRegisterEventSourceW = modadvapi32.NewProc("RegisterEventSourceW") - procDeregisterEventSource = modadvapi32.NewProc("DeregisterEventSource") - procReportEventW = modadvapi32.NewProc("ReportEventW") - procOpenSCManagerW = modadvapi32.NewProc("OpenSCManagerW") - procCloseServiceHandle = modadvapi32.NewProc("CloseServiceHandle") - procCreateServiceW = modadvapi32.NewProc("CreateServiceW") - procOpenServiceW = modadvapi32.NewProc("OpenServiceW") - procDeleteService = modadvapi32.NewProc("DeleteService") - procStartServiceW = modadvapi32.NewProc("StartServiceW") - procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus") - procControlService = modadvapi32.NewProc("ControlService") - procStartServiceCtrlDispatcherW = modadvapi32.NewProc("StartServiceCtrlDispatcherW") - procSetServiceStatus = modadvapi32.NewProc("SetServiceStatus") - procChangeServiceConfigW = modadvapi32.NewProc("ChangeServiceConfigW") - procQueryServiceConfigW = modadvapi32.NewProc("QueryServiceConfigW") - procChangeServiceConfig2W = modadvapi32.NewProc("ChangeServiceConfig2W") - procQueryServiceConfig2W = modadvapi32.NewProc("QueryServiceConfig2W") - procGetLastError = modkernel32.NewProc("GetLastError") - procLoadLibraryW = modkernel32.NewProc("LoadLibraryW") - procFreeLibrary = modkernel32.NewProc("FreeLibrary") - procGetProcAddress = modkernel32.NewProc("GetProcAddress") - procGetVersion = modkernel32.NewProc("GetVersion") - procFormatMessageW = modkernel32.NewProc("FormatMessageW") - procExitProcess = modkernel32.NewProc("ExitProcess") - procCreateFileW = modkernel32.NewProc("CreateFileW") - procReadFile = modkernel32.NewProc("ReadFile") - procWriteFile = modkernel32.NewProc("WriteFile") - procSetFilePointer = modkernel32.NewProc("SetFilePointer") - procCloseHandle = modkernel32.NewProc("CloseHandle") - procGetStdHandle = modkernel32.NewProc("GetStdHandle") - procFindFirstFileW = modkernel32.NewProc("FindFirstFileW") - procFindNextFileW = modkernel32.NewProc("FindNextFileW") - procFindClose = modkernel32.NewProc("FindClose") - procGetFileInformationByHandle = modkernel32.NewProc("GetFileInformationByHandle") - procGetCurrentDirectoryW = modkernel32.NewProc("GetCurrentDirectoryW") - procSetCurrentDirectoryW = modkernel32.NewProc("SetCurrentDirectoryW") - procCreateDirectoryW = modkernel32.NewProc("CreateDirectoryW") - procRemoveDirectoryW = modkernel32.NewProc("RemoveDirectoryW") - procDeleteFileW = modkernel32.NewProc("DeleteFileW") - procMoveFileW = modkernel32.NewProc("MoveFileW") - procGetComputerNameW = modkernel32.NewProc("GetComputerNameW") - procGetComputerNameExW = modkernel32.NewProc("GetComputerNameExW") - procSetEndOfFile = modkernel32.NewProc("SetEndOfFile") - procGetSystemTimeAsFileTime = modkernel32.NewProc("GetSystemTimeAsFileTime") - procGetTimeZoneInformation = modkernel32.NewProc("GetTimeZoneInformation") - procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort") - procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus") - procPostQueuedCompletionStatus = modkernel32.NewProc("PostQueuedCompletionStatus") - procCancelIo = modkernel32.NewProc("CancelIo") - procCancelIoEx = modkernel32.NewProc("CancelIoEx") - procCreateProcessW = modkernel32.NewProc("CreateProcessW") - procOpenProcess = modkernel32.NewProc("OpenProcess") - procTerminateProcess = modkernel32.NewProc("TerminateProcess") - procGetExitCodeProcess = modkernel32.NewProc("GetExitCodeProcess") - procGetStartupInfoW = modkernel32.NewProc("GetStartupInfoW") - procGetCurrentProcess = modkernel32.NewProc("GetCurrentProcess") - procGetProcessTimes = modkernel32.NewProc("GetProcessTimes") - procDuplicateHandle = modkernel32.NewProc("DuplicateHandle") - procWaitForSingleObject = modkernel32.NewProc("WaitForSingleObject") - procGetTempPathW = modkernel32.NewProc("GetTempPathW") - procCreatePipe = modkernel32.NewProc("CreatePipe") - procGetFileType = modkernel32.NewProc("GetFileType") - procCryptAcquireContextW = modadvapi32.NewProc("CryptAcquireContextW") - procCryptReleaseContext = modadvapi32.NewProc("CryptReleaseContext") - procCryptGenRandom = modadvapi32.NewProc("CryptGenRandom") - procGetEnvironmentStringsW = modkernel32.NewProc("GetEnvironmentStringsW") - procFreeEnvironmentStringsW = modkernel32.NewProc("FreeEnvironmentStringsW") - procGetEnvironmentVariableW = modkernel32.NewProc("GetEnvironmentVariableW") - procSetEnvironmentVariableW = modkernel32.NewProc("SetEnvironmentVariableW") - procSetFileTime = modkernel32.NewProc("SetFileTime") - procGetFileAttributesW = modkernel32.NewProc("GetFileAttributesW") - procSetFileAttributesW = modkernel32.NewProc("SetFileAttributesW") - procGetFileAttributesExW = modkernel32.NewProc("GetFileAttributesExW") - procGetCommandLineW = modkernel32.NewProc("GetCommandLineW") - procCommandLineToArgvW = modshell32.NewProc("CommandLineToArgvW") - procLocalFree = modkernel32.NewProc("LocalFree") - procSetHandleInformation = modkernel32.NewProc("SetHandleInformation") - procFlushFileBuffers = modkernel32.NewProc("FlushFileBuffers") - procGetFullPathNameW = modkernel32.NewProc("GetFullPathNameW") - procGetLongPathNameW = modkernel32.NewProc("GetLongPathNameW") - procGetShortPathNameW = modkernel32.NewProc("GetShortPathNameW") - procCreateFileMappingW = modkernel32.NewProc("CreateFileMappingW") - procMapViewOfFile = modkernel32.NewProc("MapViewOfFile") - procUnmapViewOfFile = modkernel32.NewProc("UnmapViewOfFile") - procFlushViewOfFile = modkernel32.NewProc("FlushViewOfFile") - procVirtualLock = modkernel32.NewProc("VirtualLock") - procVirtualUnlock = modkernel32.NewProc("VirtualUnlock") - procTransmitFile = modmswsock.NewProc("TransmitFile") - procReadDirectoryChangesW = modkernel32.NewProc("ReadDirectoryChangesW") - procCertOpenSystemStoreW = modcrypt32.NewProc("CertOpenSystemStoreW") - procCertOpenStore = modcrypt32.NewProc("CertOpenStore") - procCertEnumCertificatesInStore = modcrypt32.NewProc("CertEnumCertificatesInStore") - procCertAddCertificateContextToStore = modcrypt32.NewProc("CertAddCertificateContextToStore") - procCertCloseStore = modcrypt32.NewProc("CertCloseStore") - procCertGetCertificateChain = modcrypt32.NewProc("CertGetCertificateChain") - procCertFreeCertificateChain = modcrypt32.NewProc("CertFreeCertificateChain") - procCertCreateCertificateContext = modcrypt32.NewProc("CertCreateCertificateContext") - procCertFreeCertificateContext = modcrypt32.NewProc("CertFreeCertificateContext") - procCertVerifyCertificateChainPolicy = modcrypt32.NewProc("CertVerifyCertificateChainPolicy") - procRegOpenKeyExW = modadvapi32.NewProc("RegOpenKeyExW") - procRegCloseKey = modadvapi32.NewProc("RegCloseKey") - procRegQueryInfoKeyW = modadvapi32.NewProc("RegQueryInfoKeyW") - procRegEnumKeyExW = modadvapi32.NewProc("RegEnumKeyExW") - procRegQueryValueExW = modadvapi32.NewProc("RegQueryValueExW") - procGetCurrentProcessId = modkernel32.NewProc("GetCurrentProcessId") - procGetConsoleMode = modkernel32.NewProc("GetConsoleMode") - procWriteConsoleW = modkernel32.NewProc("WriteConsoleW") - procReadConsoleW = modkernel32.NewProc("ReadConsoleW") - procCreateToolhelp32Snapshot = modkernel32.NewProc("CreateToolhelp32Snapshot") - procProcess32FirstW = modkernel32.NewProc("Process32FirstW") - procProcess32NextW = modkernel32.NewProc("Process32NextW") - procDeviceIoControl = modkernel32.NewProc("DeviceIoControl") - procCreateSymbolicLinkW = modkernel32.NewProc("CreateSymbolicLinkW") - procCreateHardLinkW = modkernel32.NewProc("CreateHardLinkW") - procGetCurrentThreadId = modkernel32.NewProc("GetCurrentThreadId") - procCreateEventW = modkernel32.NewProc("CreateEventW") - procSetEvent = modkernel32.NewProc("SetEvent") - procWSAStartup = modws2_32.NewProc("WSAStartup") - procWSACleanup = modws2_32.NewProc("WSACleanup") - procWSAIoctl = modws2_32.NewProc("WSAIoctl") - procsocket = modws2_32.NewProc("socket") - procsetsockopt = modws2_32.NewProc("setsockopt") - procgetsockopt = modws2_32.NewProc("getsockopt") - procbind = modws2_32.NewProc("bind") - procconnect = modws2_32.NewProc("connect") - procgetsockname = modws2_32.NewProc("getsockname") - procgetpeername = modws2_32.NewProc("getpeername") - proclisten = modws2_32.NewProc("listen") - procshutdown = modws2_32.NewProc("shutdown") - procclosesocket = modws2_32.NewProc("closesocket") - procAcceptEx = modmswsock.NewProc("AcceptEx") - procGetAcceptExSockaddrs = modmswsock.NewProc("GetAcceptExSockaddrs") - procWSARecv = modws2_32.NewProc("WSARecv") - procWSASend = modws2_32.NewProc("WSASend") - procWSARecvFrom = modws2_32.NewProc("WSARecvFrom") - procWSASendTo = modws2_32.NewProc("WSASendTo") - procgethostbyname = modws2_32.NewProc("gethostbyname") - procgetservbyname = modws2_32.NewProc("getservbyname") - procntohs = modws2_32.NewProc("ntohs") - procgetprotobyname = modws2_32.NewProc("getprotobyname") - procDnsQuery_W = moddnsapi.NewProc("DnsQuery_W") - procDnsRecordListFree = moddnsapi.NewProc("DnsRecordListFree") - procDnsNameCompare_W = moddnsapi.NewProc("DnsNameCompare_W") - procGetAddrInfoW = modws2_32.NewProc("GetAddrInfoW") - procFreeAddrInfoW = modws2_32.NewProc("FreeAddrInfoW") - procGetIfEntry = modiphlpapi.NewProc("GetIfEntry") - procGetAdaptersInfo = modiphlpapi.NewProc("GetAdaptersInfo") - procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes") - procWSAEnumProtocolsW = modws2_32.NewProc("WSAEnumProtocolsW") - procTranslateNameW = modsecur32.NewProc("TranslateNameW") - procGetUserNameExW = modsecur32.NewProc("GetUserNameExW") - procNetUserGetInfo = modnetapi32.NewProc("NetUserGetInfo") - procNetGetJoinInformation = modnetapi32.NewProc("NetGetJoinInformation") - procNetApiBufferFree = modnetapi32.NewProc("NetApiBufferFree") - procLookupAccountSidW = modadvapi32.NewProc("LookupAccountSidW") - procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW") - procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW") - procConvertStringSidToSidW = modadvapi32.NewProc("ConvertStringSidToSidW") - procGetLengthSid = modadvapi32.NewProc("GetLengthSid") - procCopySid = modadvapi32.NewProc("CopySid") - procAllocateAndInitializeSid = modadvapi32.NewProc("AllocateAndInitializeSid") - procFreeSid = modadvapi32.NewProc("FreeSid") - procEqualSid = modadvapi32.NewProc("EqualSid") - procOpenProcessToken = modadvapi32.NewProc("OpenProcessToken") - procGetTokenInformation = modadvapi32.NewProc("GetTokenInformation") - procGetUserProfileDirectoryW = moduserenv.NewProc("GetUserProfileDirectoryW") -) - -func RegisterEventSource(uncServerName *uint16, sourceName *uint16) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall(procRegisterEventSourceW.Addr(), 2, uintptr(unsafe.Pointer(uncServerName)), uintptr(unsafe.Pointer(sourceName)), 0) - handle = Handle(r0) - if handle == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func DeregisterEventSource(handle Handle) (err error) { - r1, _, e1 := syscall.Syscall(procDeregisterEventSource.Addr(), 1, uintptr(handle), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrSId uintptr, numStrings uint16, dataSize uint32, strings **uint16, rawData *byte) (err error) { - r1, _, e1 := syscall.Syscall9(procReportEventW.Addr(), 9, uintptr(log), uintptr(etype), uintptr(category), uintptr(eventId), uintptr(usrSId), uintptr(numStrings), uintptr(dataSize), uintptr(unsafe.Pointer(strings)), uintptr(unsafe.Pointer(rawData))) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall(procOpenSCManagerW.Addr(), 3, uintptr(unsafe.Pointer(machineName)), uintptr(unsafe.Pointer(databaseName)), uintptr(access)) - handle = Handle(r0) - if handle == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CloseServiceHandle(handle Handle) (err error) { - r1, _, e1 := syscall.Syscall(procCloseServiceHandle.Addr(), 1, uintptr(handle), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access uint32, srvType uint32, startType uint32, errCtl uint32, pathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall15(procCreateServiceW.Addr(), 13, uintptr(mgr), uintptr(unsafe.Pointer(serviceName)), uintptr(unsafe.Pointer(displayName)), uintptr(access), uintptr(srvType), uintptr(startType), uintptr(errCtl), uintptr(unsafe.Pointer(pathName)), uintptr(unsafe.Pointer(loadOrderGroup)), uintptr(unsafe.Pointer(tagId)), uintptr(unsafe.Pointer(dependencies)), uintptr(unsafe.Pointer(serviceStartName)), uintptr(unsafe.Pointer(password)), 0, 0) - handle = Handle(r0) - if handle == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func OpenService(mgr Handle, serviceName *uint16, access uint32) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall(procOpenServiceW.Addr(), 3, uintptr(mgr), uintptr(unsafe.Pointer(serviceName)), uintptr(access)) - handle = Handle(r0) - if handle == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func DeleteService(service Handle) (err error) { - r1, _, e1 := syscall.Syscall(procDeleteService.Addr(), 1, uintptr(service), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func StartService(service Handle, numArgs uint32, argVectors **uint16) (err error) { - r1, _, e1 := syscall.Syscall(procStartServiceW.Addr(), 3, uintptr(service), uintptr(numArgs), uintptr(unsafe.Pointer(argVectors))) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error) { - r1, _, e1 := syscall.Syscall(procQueryServiceStatus.Addr(), 2, uintptr(service), uintptr(unsafe.Pointer(status)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err error) { - r1, _, e1 := syscall.Syscall(procControlService.Addr(), 3, uintptr(service), uintptr(control), uintptr(unsafe.Pointer(status))) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func StartServiceCtrlDispatcher(serviceTable *SERVICE_TABLE_ENTRY) (err error) { - r1, _, e1 := syscall.Syscall(procStartServiceCtrlDispatcherW.Addr(), 1, uintptr(unsafe.Pointer(serviceTable)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func SetServiceStatus(service Handle, serviceStatus *SERVICE_STATUS) (err error) { - r1, _, e1 := syscall.Syscall(procSetServiceStatus.Addr(), 2, uintptr(service), uintptr(unsafe.Pointer(serviceStatus)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, errorControl uint32, binaryPathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16, displayName *uint16) (err error) { - r1, _, e1 := syscall.Syscall12(procChangeServiceConfigW.Addr(), 11, uintptr(service), uintptr(serviceType), uintptr(startType), uintptr(errorControl), uintptr(unsafe.Pointer(binaryPathName)), uintptr(unsafe.Pointer(loadOrderGroup)), uintptr(unsafe.Pointer(tagId)), uintptr(unsafe.Pointer(dependencies)), uintptr(unsafe.Pointer(serviceStartName)), uintptr(unsafe.Pointer(password)), uintptr(unsafe.Pointer(displayName)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func QueryServiceConfig(service Handle, serviceConfig *QUERY_SERVICE_CONFIG, bufSize uint32, bytesNeeded *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procQueryServiceConfigW.Addr(), 4, uintptr(service), uintptr(unsafe.Pointer(serviceConfig)), uintptr(bufSize), uintptr(unsafe.Pointer(bytesNeeded)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error) { - r1, _, e1 := syscall.Syscall(procChangeServiceConfig2W.Addr(), 3, uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(info))) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procQueryServiceConfig2W.Addr(), 5, uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(buff)), uintptr(buffSize), uintptr(unsafe.Pointer(bytesNeeded)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetLastError() (lasterr error) { - r0, _, _ := syscall.Syscall(procGetLastError.Addr(), 0, 0, 0, 0) - if r0 != 0 { - lasterr = syscall.Errno(r0) - } - return -} - -func LoadLibrary(libname string) (handle Handle, err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(libname) - if err != nil { - return - } - return _LoadLibrary(_p0) -} - -func _LoadLibrary(libname *uint16) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall(procLoadLibraryW.Addr(), 1, uintptr(unsafe.Pointer(libname)), 0, 0) - handle = Handle(r0) - if handle == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func FreeLibrary(handle Handle) (err error) { - r1, _, e1 := syscall.Syscall(procFreeLibrary.Addr(), 1, uintptr(handle), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetProcAddress(module Handle, procname string) (proc uintptr, err error) { - var _p0 *byte - _p0, err = syscall.BytePtrFromString(procname) - if err != nil { - return - } - return _GetProcAddress(module, _p0) -} - -func _GetProcAddress(module Handle, procname *byte) (proc uintptr, err error) { - r0, _, e1 := syscall.Syscall(procGetProcAddress.Addr(), 2, uintptr(module), uintptr(unsafe.Pointer(procname)), 0) - proc = uintptr(r0) - if proc == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetVersion() (ver uint32, err error) { - r0, _, e1 := syscall.Syscall(procGetVersion.Addr(), 0, 0, 0, 0) - ver = uint32(r0) - if ver == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func FormatMessage(flags uint32, msgsrc uint32, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) { - var _p0 *uint16 - if len(buf) > 0 { - _p0 = &buf[0] - } - r0, _, e1 := syscall.Syscall9(procFormatMessageW.Addr(), 7, uintptr(flags), uintptr(msgsrc), uintptr(msgid), uintptr(langid), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(args)), 0, 0) - n = uint32(r0) - if n == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func ExitProcess(exitcode uint32) { - syscall.Syscall(procExitProcess.Addr(), 1, uintptr(exitcode), 0, 0) - return -} - -func CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile int32) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile), 0, 0) - handle = Handle(r0) - if handle == InvalidHandle { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func ReadFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) { - var _p0 *byte - if len(buf) > 0 { - _p0 = &buf[0] - } - r1, _, e1 := syscall.Syscall6(procReadFile.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(done)), uintptr(unsafe.Pointer(overlapped)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func WriteFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) { - var _p0 *byte - if len(buf) > 0 { - _p0 = &buf[0] - } - r1, _, e1 := syscall.Syscall6(procWriteFile.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(done)), uintptr(unsafe.Pointer(overlapped)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) { - r0, _, e1 := syscall.Syscall6(procSetFilePointer.Addr(), 4, uintptr(handle), uintptr(lowoffset), uintptr(unsafe.Pointer(highoffsetptr)), uintptr(whence), 0, 0) - newlowoffset = uint32(r0) - if newlowoffset == 0xffffffff { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CloseHandle(handle Handle) (err error) { - r1, _, e1 := syscall.Syscall(procCloseHandle.Addr(), 1, uintptr(handle), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetStdHandle(stdhandle int) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall(procGetStdHandle.Addr(), 1, uintptr(stdhandle), 0, 0) - handle = Handle(r0) - if handle == InvalidHandle { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall(procFindFirstFileW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(data)), 0) - handle = Handle(r0) - if handle == InvalidHandle { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func findNextFile1(handle Handle, data *win32finddata1) (err error) { - r1, _, e1 := syscall.Syscall(procFindNextFileW.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(data)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func FindClose(handle Handle) (err error) { - r1, _, e1 := syscall.Syscall(procFindClose.Addr(), 1, uintptr(handle), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error) { - r1, _, e1 := syscall.Syscall(procGetFileInformationByHandle.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(data)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) { - r0, _, e1 := syscall.Syscall(procGetCurrentDirectoryW.Addr(), 2, uintptr(buflen), uintptr(unsafe.Pointer(buf)), 0) - n = uint32(r0) - if n == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func SetCurrentDirectory(path *uint16) (err error) { - r1, _, e1 := syscall.Syscall(procSetCurrentDirectoryW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) { - r1, _, e1 := syscall.Syscall(procCreateDirectoryW.Addr(), 2, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(sa)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func RemoveDirectory(path *uint16) (err error) { - r1, _, e1 := syscall.Syscall(procRemoveDirectoryW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func DeleteFile(path *uint16) (err error) { - r1, _, e1 := syscall.Syscall(procDeleteFileW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func MoveFile(from *uint16, to *uint16) (err error) { - r1, _, e1 := syscall.Syscall(procMoveFileW.Addr(), 2, uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetComputerName(buf *uint16, n *uint32) (err error) { - r1, _, e1 := syscall.Syscall(procGetComputerNameW.Addr(), 2, uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(n)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) { - r1, _, e1 := syscall.Syscall(procGetComputerNameExW.Addr(), 3, uintptr(nametype), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(n))) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func SetEndOfFile(handle Handle) (err error) { - r1, _, e1 := syscall.Syscall(procSetEndOfFile.Addr(), 1, uintptr(handle), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetSystemTimeAsFileTime(time *Filetime) { - syscall.Syscall(procGetSystemTimeAsFileTime.Addr(), 1, uintptr(unsafe.Pointer(time)), 0, 0) - return -} - -func GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) { - r0, _, e1 := syscall.Syscall(procGetTimeZoneInformation.Addr(), 1, uintptr(unsafe.Pointer(tzi)), 0, 0) - rc = uint32(r0) - if rc == 0xffffffff { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uint32, threadcnt uint32) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall6(procCreateIoCompletionPort.Addr(), 4, uintptr(filehandle), uintptr(cphandle), uintptr(key), uintptr(threadcnt), 0, 0) - handle = Handle(r0) - if handle == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uint32, overlapped **Overlapped, timeout uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetQueuedCompletionStatus.Addr(), 5, uintptr(cphandle), uintptr(unsafe.Pointer(qty)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(overlapped)), uintptr(timeout), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uint32, overlapped *Overlapped) (err error) { - r1, _, e1 := syscall.Syscall6(procPostQueuedCompletionStatus.Addr(), 4, uintptr(cphandle), uintptr(qty), uintptr(key), uintptr(unsafe.Pointer(overlapped)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CancelIo(s Handle) (err error) { - r1, _, e1 := syscall.Syscall(procCancelIo.Addr(), 1, uintptr(s), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CancelIoEx(s Handle, o *Overlapped) (err error) { - r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(s), uintptr(unsafe.Pointer(o)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) { - var _p0 uint32 - if inheritHandles { - _p0 = 1 - } else { - _p0 = 0 - } - r1, _, e1 := syscall.Syscall12(procCreateProcessW.Addr(), 10, uintptr(unsafe.Pointer(appName)), uintptr(unsafe.Pointer(commandLine)), uintptr(unsafe.Pointer(procSecurity)), uintptr(unsafe.Pointer(threadSecurity)), uintptr(_p0), uintptr(creationFlags), uintptr(unsafe.Pointer(env)), uintptr(unsafe.Pointer(currentDir)), uintptr(unsafe.Pointer(startupInfo)), uintptr(unsafe.Pointer(outProcInfo)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func OpenProcess(da uint32, inheritHandle bool, pid uint32) (handle Handle, err error) { - var _p0 uint32 - if inheritHandle { - _p0 = 1 - } else { - _p0 = 0 - } - r0, _, e1 := syscall.Syscall(procOpenProcess.Addr(), 3, uintptr(da), uintptr(_p0), uintptr(pid)) - handle = Handle(r0) - if handle == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func TerminateProcess(handle Handle, exitcode uint32) (err error) { - r1, _, e1 := syscall.Syscall(procTerminateProcess.Addr(), 2, uintptr(handle), uintptr(exitcode), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetExitCodeProcess(handle Handle, exitcode *uint32) (err error) { - r1, _, e1 := syscall.Syscall(procGetExitCodeProcess.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(exitcode)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetStartupInfo(startupInfo *StartupInfo) (err error) { - r1, _, e1 := syscall.Syscall(procGetStartupInfoW.Addr(), 1, uintptr(unsafe.Pointer(startupInfo)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetCurrentProcess() (pseudoHandle Handle, err error) { - r0, _, e1 := syscall.Syscall(procGetCurrentProcess.Addr(), 0, 0, 0, 0) - pseudoHandle = Handle(r0) - if pseudoHandle == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error) { - r1, _, e1 := syscall.Syscall6(procGetProcessTimes.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(creationTime)), uintptr(unsafe.Pointer(exitTime)), uintptr(unsafe.Pointer(kernelTime)), uintptr(unsafe.Pointer(userTime)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error) { - var _p0 uint32 - if bInheritHandle { - _p0 = 1 - } else { - _p0 = 0 - } - r1, _, e1 := syscall.Syscall9(procDuplicateHandle.Addr(), 7, uintptr(hSourceProcessHandle), uintptr(hSourceHandle), uintptr(hTargetProcessHandle), uintptr(unsafe.Pointer(lpTargetHandle)), uintptr(dwDesiredAccess), uintptr(_p0), uintptr(dwOptions), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) { - r0, _, e1 := syscall.Syscall(procWaitForSingleObject.Addr(), 2, uintptr(handle), uintptr(waitMilliseconds), 0) - event = uint32(r0) - if event == 0xffffffff { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) { - r0, _, e1 := syscall.Syscall(procGetTempPathW.Addr(), 2, uintptr(buflen), uintptr(unsafe.Pointer(buf)), 0) - n = uint32(r0) - if n == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procCreatePipe.Addr(), 4, uintptr(unsafe.Pointer(readhandle)), uintptr(unsafe.Pointer(writehandle)), uintptr(unsafe.Pointer(sa)), uintptr(size), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetFileType(filehandle Handle) (n uint32, err error) { - r0, _, e1 := syscall.Syscall(procGetFileType.Addr(), 1, uintptr(filehandle), 0, 0) - n = uint32(r0) - if n == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procCryptAcquireContextW.Addr(), 5, uintptr(unsafe.Pointer(provhandle)), uintptr(unsafe.Pointer(container)), uintptr(unsafe.Pointer(provider)), uintptr(provtype), uintptr(flags), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CryptReleaseContext(provhandle Handle, flags uint32) (err error) { - r1, _, e1 := syscall.Syscall(procCryptReleaseContext.Addr(), 2, uintptr(provhandle), uintptr(flags), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) { - r1, _, e1 := syscall.Syscall(procCryptGenRandom.Addr(), 3, uintptr(provhandle), uintptr(buflen), uintptr(unsafe.Pointer(buf))) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetEnvironmentStrings() (envs *uint16, err error) { - r0, _, e1 := syscall.Syscall(procGetEnvironmentStringsW.Addr(), 0, 0, 0, 0) - envs = (*uint16)(unsafe.Pointer(r0)) - if envs == nil { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func FreeEnvironmentStrings(envs *uint16) (err error) { - r1, _, e1 := syscall.Syscall(procFreeEnvironmentStringsW.Addr(), 1, uintptr(unsafe.Pointer(envs)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) { - r0, _, e1 := syscall.Syscall(procGetEnvironmentVariableW.Addr(), 3, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buffer)), uintptr(size)) - n = uint32(r0) - if n == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func SetEnvironmentVariable(name *uint16, value *uint16) (err error) { - r1, _, e1 := syscall.Syscall(procSetEnvironmentVariableW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(value)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) { - r1, _, e1 := syscall.Syscall6(procSetFileTime.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(ctime)), uintptr(unsafe.Pointer(atime)), uintptr(unsafe.Pointer(wtime)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetFileAttributes(name *uint16) (attrs uint32, err error) { - r0, _, e1 := syscall.Syscall(procGetFileAttributesW.Addr(), 1, uintptr(unsafe.Pointer(name)), 0, 0) - attrs = uint32(r0) - if attrs == INVALID_FILE_ATTRIBUTES { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func SetFileAttributes(name *uint16, attrs uint32) (err error) { - r1, _, e1 := syscall.Syscall(procSetFileAttributesW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(attrs), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) { - r1, _, e1 := syscall.Syscall(procGetFileAttributesExW.Addr(), 3, uintptr(unsafe.Pointer(name)), uintptr(level), uintptr(unsafe.Pointer(info))) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetCommandLine() (cmd *uint16) { - r0, _, _ := syscall.Syscall(procGetCommandLineW.Addr(), 0, 0, 0, 0) - cmd = (*uint16)(unsafe.Pointer(r0)) - return -} - -func CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) { - r0, _, e1 := syscall.Syscall(procCommandLineToArgvW.Addr(), 2, uintptr(unsafe.Pointer(cmd)), uintptr(unsafe.Pointer(argc)), 0) - argv = (*[8192]*[8192]uint16)(unsafe.Pointer(r0)) - if argv == nil { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func LocalFree(hmem Handle) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall(procLocalFree.Addr(), 1, uintptr(hmem), 0, 0) - handle = Handle(r0) - if handle != 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error) { - r1, _, e1 := syscall.Syscall(procSetHandleInformation.Addr(), 3, uintptr(handle), uintptr(mask), uintptr(flags)) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func FlushFileBuffers(handle Handle) (err error) { - r1, _, e1 := syscall.Syscall(procFlushFileBuffers.Addr(), 1, uintptr(handle), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) { - r0, _, e1 := syscall.Syscall6(procGetFullPathNameW.Addr(), 4, uintptr(unsafe.Pointer(path)), uintptr(buflen), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(fname)), 0, 0) - n = uint32(r0) - if n == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) { - r0, _, e1 := syscall.Syscall(procGetLongPathNameW.Addr(), 3, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(buf)), uintptr(buflen)) - n = uint32(r0) - if n == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) { - r0, _, e1 := syscall.Syscall(procGetShortPathNameW.Addr(), 3, uintptr(unsafe.Pointer(longpath)), uintptr(unsafe.Pointer(shortpath)), uintptr(buflen)) - n = uint32(r0) - if n == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall6(procCreateFileMappingW.Addr(), 6, uintptr(fhandle), uintptr(unsafe.Pointer(sa)), uintptr(prot), uintptr(maxSizeHigh), uintptr(maxSizeLow), uintptr(unsafe.Pointer(name))) - handle = Handle(r0) - if handle == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error) { - r0, _, e1 := syscall.Syscall6(procMapViewOfFile.Addr(), 5, uintptr(handle), uintptr(access), uintptr(offsetHigh), uintptr(offsetLow), uintptr(length), 0) - addr = uintptr(r0) - if addr == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func UnmapViewOfFile(addr uintptr) (err error) { - r1, _, e1 := syscall.Syscall(procUnmapViewOfFile.Addr(), 1, uintptr(addr), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func FlushViewOfFile(addr uintptr, length uintptr) (err error) { - r1, _, e1 := syscall.Syscall(procFlushViewOfFile.Addr(), 2, uintptr(addr), uintptr(length), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func VirtualLock(addr uintptr, length uintptr) (err error) { - r1, _, e1 := syscall.Syscall(procVirtualLock.Addr(), 2, uintptr(addr), uintptr(length), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func VirtualUnlock(addr uintptr, length uintptr) (err error) { - r1, _, e1 := syscall.Syscall(procVirtualUnlock.Addr(), 2, uintptr(addr), uintptr(length), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) { - r1, _, e1 := syscall.Syscall9(procTransmitFile.Addr(), 7, uintptr(s), uintptr(handle), uintptr(bytesToWrite), uintptr(bytsPerSend), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transmitFileBuf)), uintptr(flags), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) { - var _p0 uint32 - if watchSubTree { - _p0 = 1 - } else { - _p0 = 0 - } - r1, _, e1 := syscall.Syscall9(procReadDirectoryChangesW.Addr(), 8, uintptr(handle), uintptr(unsafe.Pointer(buf)), uintptr(buflen), uintptr(_p0), uintptr(mask), uintptr(unsafe.Pointer(retlen)), uintptr(unsafe.Pointer(overlapped)), uintptr(completionRoutine), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) { - r0, _, e1 := syscall.Syscall(procCertOpenSystemStoreW.Addr(), 2, uintptr(hprov), uintptr(unsafe.Pointer(name)), 0) - store = Handle(r0) - if store == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall6(procCertOpenStore.Addr(), 5, uintptr(storeProvider), uintptr(msgAndCertEncodingType), uintptr(cryptProv), uintptr(flags), uintptr(para), 0) - handle = Handle(r0) - if handle == InvalidHandle { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) { - r0, _, e1 := syscall.Syscall(procCertEnumCertificatesInStore.Addr(), 2, uintptr(store), uintptr(unsafe.Pointer(prevContext)), 0) - context = (*CertContext)(unsafe.Pointer(r0)) - if context == nil { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) { - r1, _, e1 := syscall.Syscall6(procCertAddCertificateContextToStore.Addr(), 4, uintptr(store), uintptr(unsafe.Pointer(certContext)), uintptr(addDisposition), uintptr(unsafe.Pointer(storeContext)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CertCloseStore(store Handle, flags uint32) (err error) { - r1, _, e1 := syscall.Syscall(procCertCloseStore.Addr(), 2, uintptr(store), uintptr(flags), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) { - r1, _, e1 := syscall.Syscall9(procCertGetCertificateChain.Addr(), 8, uintptr(engine), uintptr(unsafe.Pointer(leaf)), uintptr(unsafe.Pointer(time)), uintptr(additionalStore), uintptr(unsafe.Pointer(para)), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(chainCtx)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CertFreeCertificateChain(ctx *CertChainContext) { - syscall.Syscall(procCertFreeCertificateChain.Addr(), 1, uintptr(unsafe.Pointer(ctx)), 0, 0) - return -} - -func CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) { - r0, _, e1 := syscall.Syscall(procCertCreateCertificateContext.Addr(), 3, uintptr(certEncodingType), uintptr(unsafe.Pointer(certEncoded)), uintptr(encodedLen)) - context = (*CertContext)(unsafe.Pointer(r0)) - if context == nil { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CertFreeCertificateContext(ctx *CertContext) (err error) { - r1, _, e1 := syscall.Syscall(procCertFreeCertificateContext.Addr(), 1, uintptr(unsafe.Pointer(ctx)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) { - r1, _, e1 := syscall.Syscall6(procCertVerifyCertificateChainPolicy.Addr(), 4, uintptr(policyOID), uintptr(unsafe.Pointer(chain)), uintptr(unsafe.Pointer(para)), uintptr(unsafe.Pointer(status)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) { - r0, _, _ := syscall.Syscall6(procRegOpenKeyExW.Addr(), 5, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(options), uintptr(desiredAccess), uintptr(unsafe.Pointer(result)), 0) - if r0 != 0 { - regerrno = syscall.Errno(r0) - } - return -} - -func RegCloseKey(key Handle) (regerrno error) { - r0, _, _ := syscall.Syscall(procRegCloseKey.Addr(), 1, uintptr(key), 0, 0) - if r0 != 0 { - regerrno = syscall.Errno(r0) - } - return -} - -func RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) { - r0, _, _ := syscall.Syscall12(procRegQueryInfoKeyW.Addr(), 12, uintptr(key), uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(classLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(subkeysLen)), uintptr(unsafe.Pointer(maxSubkeyLen)), uintptr(unsafe.Pointer(maxClassLen)), uintptr(unsafe.Pointer(valuesLen)), uintptr(unsafe.Pointer(maxValueNameLen)), uintptr(unsafe.Pointer(maxValueLen)), uintptr(unsafe.Pointer(saLen)), uintptr(unsafe.Pointer(lastWriteTime))) - if r0 != 0 { - regerrno = syscall.Errno(r0) - } - return -} - -func RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) { - r0, _, _ := syscall.Syscall9(procRegEnumKeyExW.Addr(), 8, uintptr(key), uintptr(index), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(classLen)), uintptr(unsafe.Pointer(lastWriteTime)), 0) - if r0 != 0 { - regerrno = syscall.Errno(r0) - } - return -} - -func RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) { - r0, _, _ := syscall.Syscall6(procRegQueryValueExW.Addr(), 6, uintptr(key), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen))) - if r0 != 0 { - regerrno = syscall.Errno(r0) - } - return -} - -func getCurrentProcessId() (pid uint32) { - r0, _, _ := syscall.Syscall(procGetCurrentProcessId.Addr(), 0, 0, 0, 0) - pid = uint32(r0) - return -} - -func GetConsoleMode(console Handle, mode *uint32) (err error) { - r1, _, e1 := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(console), uintptr(unsafe.Pointer(mode)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) { - r1, _, e1 := syscall.Syscall6(procWriteConsoleW.Addr(), 5, uintptr(console), uintptr(unsafe.Pointer(buf)), uintptr(towrite), uintptr(unsafe.Pointer(written)), uintptr(unsafe.Pointer(reserved)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) { - r1, _, e1 := syscall.Syscall6(procReadConsoleW.Addr(), 5, uintptr(console), uintptr(unsafe.Pointer(buf)), uintptr(toread), uintptr(unsafe.Pointer(read)), uintptr(unsafe.Pointer(inputControl)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall(procCreateToolhelp32Snapshot.Addr(), 2, uintptr(flags), uintptr(processId), 0) - handle = Handle(r0) - if handle == InvalidHandle { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) { - r1, _, e1 := syscall.Syscall(procProcess32FirstW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(procEntry)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) { - r1, _, e1 := syscall.Syscall(procProcess32NextW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(procEntry)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error) { - r1, _, e1 := syscall.Syscall9(procDeviceIoControl.Addr(), 8, uintptr(handle), uintptr(ioControlCode), uintptr(unsafe.Pointer(inBuffer)), uintptr(inBufferSize), uintptr(unsafe.Pointer(outBuffer)), uintptr(outBufferSize), uintptr(unsafe.Pointer(bytesReturned)), uintptr(unsafe.Pointer(overlapped)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) { - r1, _, e1 := syscall.Syscall(procCreateSymbolicLinkW.Addr(), 3, uintptr(unsafe.Pointer(symlinkfilename)), uintptr(unsafe.Pointer(targetfilename)), uintptr(flags)) - if r1&0xff == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) { - r1, _, e1 := syscall.Syscall(procCreateHardLinkW.Addr(), 3, uintptr(unsafe.Pointer(filename)), uintptr(unsafe.Pointer(existingfilename)), uintptr(reserved)) - if r1&0xff == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetCurrentThreadId() (id uint32) { - r0, _, _ := syscall.Syscall(procGetCurrentThreadId.Addr(), 0, 0, 0, 0) - id = uint32(r0) - return -} - -func CreateEvent(eventAttrs *syscall.SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(eventAttrs)), uintptr(manualReset), uintptr(initialState), uintptr(unsafe.Pointer(name)), 0, 0) - handle = Handle(r0) - if handle == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func SetEvent(event Handle) (err error) { - r1, _, e1 := syscall.Syscall(procSetEvent.Addr(), 1, uintptr(event), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func WSAStartup(verreq uint32, data *WSAData) (sockerr error) { - r0, _, _ := syscall.Syscall(procWSAStartup.Addr(), 2, uintptr(verreq), uintptr(unsafe.Pointer(data)), 0) - if r0 != 0 { - sockerr = syscall.Errno(r0) - } - return -} - -func WSACleanup() (err error) { - r1, _, e1 := syscall.Syscall(procWSACleanup.Addr(), 0, 0, 0, 0) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) { - r1, _, e1 := syscall.Syscall9(procWSAIoctl.Addr(), 9, uintptr(s), uintptr(iocc), uintptr(unsafe.Pointer(inbuf)), uintptr(cbif), uintptr(unsafe.Pointer(outbuf)), uintptr(cbob), uintptr(unsafe.Pointer(cbbr)), uintptr(unsafe.Pointer(overlapped)), uintptr(completionRoutine)) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func socket(af int32, typ int32, protocol int32) (handle Handle, err error) { - r0, _, e1 := syscall.Syscall(procsocket.Addr(), 3, uintptr(af), uintptr(typ), uintptr(protocol)) - handle = Handle(r0) - if handle == InvalidHandle { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) { - r1, _, e1 := syscall.Syscall6(procsetsockopt.Addr(), 5, uintptr(s), uintptr(level), uintptr(optname), uintptr(unsafe.Pointer(optval)), uintptr(optlen), 0) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) { - r1, _, e1 := syscall.Syscall6(procgetsockopt.Addr(), 5, uintptr(s), uintptr(level), uintptr(optname), uintptr(unsafe.Pointer(optval)), uintptr(unsafe.Pointer(optlen)), 0) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func bind(s Handle, name unsafe.Pointer, namelen int32) (err error) { - r1, _, e1 := syscall.Syscall(procbind.Addr(), 3, uintptr(s), uintptr(name), uintptr(namelen)) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func connect(s Handle, name unsafe.Pointer, namelen int32) (err error) { - r1, _, e1 := syscall.Syscall(procconnect.Addr(), 3, uintptr(s), uintptr(name), uintptr(namelen)) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) { - r1, _, e1 := syscall.Syscall(procgetsockname.Addr(), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) { - r1, _, e1 := syscall.Syscall(procgetpeername.Addr(), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func listen(s Handle, backlog int32) (err error) { - r1, _, e1 := syscall.Syscall(proclisten.Addr(), 2, uintptr(s), uintptr(backlog), 0) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func shutdown(s Handle, how int32) (err error) { - r1, _, e1 := syscall.Syscall(procshutdown.Addr(), 2, uintptr(s), uintptr(how), 0) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func Closesocket(s Handle) (err error) { - r1, _, e1 := syscall.Syscall(procclosesocket.Addr(), 1, uintptr(s), 0, 0) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) { - r1, _, e1 := syscall.Syscall9(procAcceptEx.Addr(), 8, uintptr(ls), uintptr(as), uintptr(unsafe.Pointer(buf)), uintptr(rxdatalen), uintptr(laddrlen), uintptr(raddrlen), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(overlapped)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) { - syscall.Syscall9(procGetAcceptExSockaddrs.Addr(), 8, uintptr(unsafe.Pointer(buf)), uintptr(rxdatalen), uintptr(laddrlen), uintptr(raddrlen), uintptr(unsafe.Pointer(lrsa)), uintptr(unsafe.Pointer(lrsalen)), uintptr(unsafe.Pointer(rrsa)), uintptr(unsafe.Pointer(rrsalen)), 0) - return -} - -func WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) { - r1, _, e1 := syscall.Syscall9(procWSARecv.Addr(), 7, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0, 0) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) { - r1, _, e1 := syscall.Syscall9(procWSASend.Addr(), 7, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(sent)), uintptr(flags), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0, 0) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error) { - r1, _, e1 := syscall.Syscall9(procWSARecvFrom.Addr(), 9, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine))) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32, overlapped *Overlapped, croutine *byte) (err error) { - r1, _, e1 := syscall.Syscall9(procWSASendTo.Addr(), 9, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(sent)), uintptr(flags), uintptr(unsafe.Pointer(to)), uintptr(tolen), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine))) - if r1 == socket_error { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetHostByName(name string) (h *Hostent, err error) { - var _p0 *byte - _p0, err = syscall.BytePtrFromString(name) - if err != nil { - return - } - return _GetHostByName(_p0) -} - -func _GetHostByName(name *byte) (h *Hostent, err error) { - r0, _, e1 := syscall.Syscall(procgethostbyname.Addr(), 1, uintptr(unsafe.Pointer(name)), 0, 0) - h = (*Hostent)(unsafe.Pointer(r0)) - if h == nil { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetServByName(name string, proto string) (s *Servent, err error) { - var _p0 *byte - _p0, err = syscall.BytePtrFromString(name) - if err != nil { - return - } - var _p1 *byte - _p1, err = syscall.BytePtrFromString(proto) - if err != nil { - return - } - return _GetServByName(_p0, _p1) -} - -func _GetServByName(name *byte, proto *byte) (s *Servent, err error) { - r0, _, e1 := syscall.Syscall(procgetservbyname.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(proto)), 0) - s = (*Servent)(unsafe.Pointer(r0)) - if s == nil { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func Ntohs(netshort uint16) (u uint16) { - r0, _, _ := syscall.Syscall(procntohs.Addr(), 1, uintptr(netshort), 0, 0) - u = uint16(r0) - return -} - -func GetProtoByName(name string) (p *Protoent, err error) { - var _p0 *byte - _p0, err = syscall.BytePtrFromString(name) - if err != nil { - return - } - return _GetProtoByName(_p0) -} - -func _GetProtoByName(name *byte) (p *Protoent, err error) { - r0, _, e1 := syscall.Syscall(procgetprotobyname.Addr(), 1, uintptr(unsafe.Pointer(name)), 0, 0) - p = (*Protoent)(unsafe.Pointer(r0)) - if p == nil { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) { - var _p0 *uint16 - _p0, status = syscall.UTF16PtrFromString(name) - if status != nil { - return - } - return _DnsQuery(_p0, qtype, options, extra, qrs, pr) -} - -func _DnsQuery(name *uint16, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) { - r0, _, _ := syscall.Syscall6(procDnsQuery_W.Addr(), 6, uintptr(unsafe.Pointer(name)), uintptr(qtype), uintptr(options), uintptr(unsafe.Pointer(extra)), uintptr(unsafe.Pointer(qrs)), uintptr(unsafe.Pointer(pr))) - if r0 != 0 { - status = syscall.Errno(r0) - } - return -} - -func DnsRecordListFree(rl *DNSRecord, freetype uint32) { - syscall.Syscall(procDnsRecordListFree.Addr(), 2, uintptr(unsafe.Pointer(rl)), uintptr(freetype), 0) - return -} - -func DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) { - r0, _, _ := syscall.Syscall(procDnsNameCompare_W.Addr(), 2, uintptr(unsafe.Pointer(name1)), uintptr(unsafe.Pointer(name2)), 0) - same = r0 != 0 - return -} - -func GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) { - r0, _, _ := syscall.Syscall6(procGetAddrInfoW.Addr(), 4, uintptr(unsafe.Pointer(nodename)), uintptr(unsafe.Pointer(servicename)), uintptr(unsafe.Pointer(hints)), uintptr(unsafe.Pointer(result)), 0, 0) - if r0 != 0 { - sockerr = syscall.Errno(r0) - } - return -} - -func FreeAddrInfoW(addrinfo *AddrinfoW) { - syscall.Syscall(procFreeAddrInfoW.Addr(), 1, uintptr(unsafe.Pointer(addrinfo)), 0, 0) - return -} - -func GetIfEntry(pIfRow *MibIfRow) (errcode error) { - r0, _, _ := syscall.Syscall(procGetIfEntry.Addr(), 1, uintptr(unsafe.Pointer(pIfRow)), 0, 0) - if r0 != 0 { - errcode = syscall.Errno(r0) - } - return -} - -func GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) { - r0, _, _ := syscall.Syscall(procGetAdaptersInfo.Addr(), 2, uintptr(unsafe.Pointer(ai)), uintptr(unsafe.Pointer(ol)), 0) - if r0 != 0 { - errcode = syscall.Errno(r0) - } - return -} - -func SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) { - r1, _, e1 := syscall.Syscall(procSetFileCompletionNotificationModes.Addr(), 2, uintptr(handle), uintptr(flags), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) { - r0, _, e1 := syscall.Syscall(procWSAEnumProtocolsW.Addr(), 3, uintptr(unsafe.Pointer(protocols)), uintptr(unsafe.Pointer(protocolBuffer)), uintptr(unsafe.Pointer(bufferLength))) - n = int32(r0) - if n == -1 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func TranslateName(accName *uint16, accNameFormat uint32, desiredNameFormat uint32, translatedName *uint16, nSize *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procTranslateNameW.Addr(), 5, uintptr(unsafe.Pointer(accName)), uintptr(accNameFormat), uintptr(desiredNameFormat), uintptr(unsafe.Pointer(translatedName)), uintptr(unsafe.Pointer(nSize)), 0) - if r1&0xff == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetUserNameEx(nameFormat uint32, nameBuffre *uint16, nSize *uint32) (err error) { - r1, _, e1 := syscall.Syscall(procGetUserNameExW.Addr(), 3, uintptr(nameFormat), uintptr(unsafe.Pointer(nameBuffre)), uintptr(unsafe.Pointer(nSize))) - if r1&0xff == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) { - r0, _, _ := syscall.Syscall6(procNetUserGetInfo.Addr(), 4, uintptr(unsafe.Pointer(serverName)), uintptr(unsafe.Pointer(userName)), uintptr(level), uintptr(unsafe.Pointer(buf)), 0, 0) - if r0 != 0 { - neterr = syscall.Errno(r0) - } - return -} - -func NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) { - r0, _, _ := syscall.Syscall(procNetGetJoinInformation.Addr(), 3, uintptr(unsafe.Pointer(server)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(bufType))) - if r0 != 0 { - neterr = syscall.Errno(r0) - } - return -} - -func NetApiBufferFree(buf *byte) (neterr error) { - r0, _, _ := syscall.Syscall(procNetApiBufferFree.Addr(), 1, uintptr(unsafe.Pointer(buf)), 0, 0) - if r0 != 0 { - neterr = syscall.Errno(r0) - } - return -} - -func LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) { - r1, _, e1 := syscall.Syscall9(procLookupAccountSidW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(refdDomainName)), uintptr(unsafe.Pointer(refdDomainNameLen)), uintptr(unsafe.Pointer(use)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) { - r1, _, e1 := syscall.Syscall9(procLookupAccountNameW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(accountName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sidLen)), uintptr(unsafe.Pointer(refdDomainName)), uintptr(unsafe.Pointer(refdDomainNameLen)), uintptr(unsafe.Pointer(use)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) { - r1, _, e1 := syscall.Syscall(procConvertSidToStringSidW.Addr(), 2, uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(stringSid)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) { - r1, _, e1 := syscall.Syscall(procConvertStringSidToSidW.Addr(), 2, uintptr(unsafe.Pointer(stringSid)), uintptr(unsafe.Pointer(sid)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetLengthSid(sid *SID) (len uint32) { - r0, _, _ := syscall.Syscall(procGetLengthSid.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0) - len = uint32(r0) - return -} - -func CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error) { - r1, _, e1 := syscall.Syscall(procCopySid.Addr(), 3, uintptr(destSidLen), uintptr(unsafe.Pointer(destSid)), uintptr(unsafe.Pointer(srcSid))) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error) { - r1, _, e1 := syscall.Syscall12(procAllocateAndInitializeSid.Addr(), 11, uintptr(unsafe.Pointer(identAuth)), uintptr(subAuth), uintptr(subAuth0), uintptr(subAuth1), uintptr(subAuth2), uintptr(subAuth3), uintptr(subAuth4), uintptr(subAuth5), uintptr(subAuth6), uintptr(subAuth7), uintptr(unsafe.Pointer(sid)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func FreeSid(sid *SID) (err error) { - r1, _, e1 := syscall.Syscall(procFreeSid.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0) - if r1 != 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) { - r0, _, _ := syscall.Syscall(procEqualSid.Addr(), 2, uintptr(unsafe.Pointer(sid1)), uintptr(unsafe.Pointer(sid2)), 0) - isEqual = r0 != 0 - return -} - -func OpenProcessToken(h Handle, access uint32, token *Token) (err error) { - r1, _, e1 := syscall.Syscall(procOpenProcessToken.Addr(), 3, uintptr(h), uintptr(access), uintptr(unsafe.Pointer(token))) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetTokenInformation(t Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetTokenInformation.Addr(), 5, uintptr(t), uintptr(infoClass), uintptr(unsafe.Pointer(info)), uintptr(infoLen), uintptr(unsafe.Pointer(returnedLen)), 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) { - r1, _, e1 := syscall.Syscall(procGetUserProfileDirectoryW.Addr(), 3, uintptr(t), uintptr(unsafe.Pointer(dir)), uintptr(unsafe.Pointer(dirLen))) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/ztypes_windows.go b/Godeps/_workspace/src/golang.org/x/sys/windows/ztypes_windows.go deleted file mode 100644 index ea600f6..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/ztypes_windows.go +++ /dev/null @@ -1,1137 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package windows - -import "syscall" - -const ( - // Windows errors. - ERROR_FILE_NOT_FOUND syscall.Errno = 2 - ERROR_PATH_NOT_FOUND syscall.Errno = 3 - ERROR_ACCESS_DENIED syscall.Errno = 5 - ERROR_NO_MORE_FILES syscall.Errno = 18 - ERROR_HANDLE_EOF syscall.Errno = 38 - ERROR_NETNAME_DELETED syscall.Errno = 64 - ERROR_FILE_EXISTS syscall.Errno = 80 - ERROR_BROKEN_PIPE syscall.Errno = 109 - ERROR_BUFFER_OVERFLOW syscall.Errno = 111 - ERROR_INSUFFICIENT_BUFFER syscall.Errno = 122 - ERROR_MOD_NOT_FOUND syscall.Errno = 126 - ERROR_PROC_NOT_FOUND syscall.Errno = 127 - ERROR_ALREADY_EXISTS syscall.Errno = 183 - ERROR_ENVVAR_NOT_FOUND syscall.Errno = 203 - ERROR_MORE_DATA syscall.Errno = 234 - ERROR_OPERATION_ABORTED syscall.Errno = 995 - ERROR_IO_PENDING syscall.Errno = 997 - ERROR_SERVICE_SPECIFIC_ERROR syscall.Errno = 1066 - ERROR_NOT_FOUND syscall.Errno = 1168 - ERROR_PRIVILEGE_NOT_HELD syscall.Errno = 1314 - WSAEACCES syscall.Errno = 10013 - WSAECONNRESET syscall.Errno = 10054 -) - -const ( - // Invented values to support what package os expects. - O_RDONLY = 0x00000 - O_WRONLY = 0x00001 - O_RDWR = 0x00002 - O_CREAT = 0x00040 - O_EXCL = 0x00080 - O_NOCTTY = 0x00100 - O_TRUNC = 0x00200 - O_NONBLOCK = 0x00800 - O_APPEND = 0x00400 - O_SYNC = 0x01000 - O_ASYNC = 0x02000 - O_CLOEXEC = 0x80000 -) - -const ( - // More invented values for signals - SIGHUP = Signal(0x1) - SIGINT = Signal(0x2) - SIGQUIT = Signal(0x3) - SIGILL = Signal(0x4) - SIGTRAP = Signal(0x5) - SIGABRT = Signal(0x6) - SIGBUS = Signal(0x7) - SIGFPE = Signal(0x8) - SIGKILL = Signal(0x9) - SIGSEGV = Signal(0xb) - SIGPIPE = Signal(0xd) - SIGALRM = Signal(0xe) - SIGTERM = Signal(0xf) -) - -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", -} - -const ( - GENERIC_READ = 0x80000000 - GENERIC_WRITE = 0x40000000 - GENERIC_EXECUTE = 0x20000000 - GENERIC_ALL = 0x10000000 - - FILE_LIST_DIRECTORY = 0x00000001 - FILE_APPEND_DATA = 0x00000004 - FILE_WRITE_ATTRIBUTES = 0x00000100 - - FILE_SHARE_READ = 0x00000001 - FILE_SHARE_WRITE = 0x00000002 - FILE_SHARE_DELETE = 0x00000004 - FILE_ATTRIBUTE_READONLY = 0x00000001 - FILE_ATTRIBUTE_HIDDEN = 0x00000002 - FILE_ATTRIBUTE_SYSTEM = 0x00000004 - FILE_ATTRIBUTE_DIRECTORY = 0x00000010 - FILE_ATTRIBUTE_ARCHIVE = 0x00000020 - FILE_ATTRIBUTE_NORMAL = 0x00000080 - FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400 - - INVALID_FILE_ATTRIBUTES = 0xffffffff - - CREATE_NEW = 1 - CREATE_ALWAYS = 2 - OPEN_EXISTING = 3 - OPEN_ALWAYS = 4 - TRUNCATE_EXISTING = 5 - - FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 - FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 - FILE_FLAG_OVERLAPPED = 0x40000000 - - HANDLE_FLAG_INHERIT = 0x00000001 - STARTF_USESTDHANDLES = 0x00000100 - STARTF_USESHOWWINDOW = 0x00000001 - DUPLICATE_CLOSE_SOURCE = 0x00000001 - DUPLICATE_SAME_ACCESS = 0x00000002 - - STD_INPUT_HANDLE = -10 - STD_OUTPUT_HANDLE = -11 - STD_ERROR_HANDLE = -12 - - FILE_BEGIN = 0 - FILE_CURRENT = 1 - FILE_END = 2 - - LANG_ENGLISH = 0x09 - SUBLANG_ENGLISH_US = 0x01 - - FORMAT_MESSAGE_ALLOCATE_BUFFER = 256 - FORMAT_MESSAGE_IGNORE_INSERTS = 512 - FORMAT_MESSAGE_FROM_STRING = 1024 - FORMAT_MESSAGE_FROM_HMODULE = 2048 - FORMAT_MESSAGE_FROM_SYSTEM = 4096 - FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192 - FORMAT_MESSAGE_MAX_WIDTH_MASK = 255 - - MAX_PATH = 260 - MAX_LONG_PATH = 32768 - - MAX_COMPUTERNAME_LENGTH = 15 - - TIME_ZONE_ID_UNKNOWN = 0 - TIME_ZONE_ID_STANDARD = 1 - - TIME_ZONE_ID_DAYLIGHT = 2 - IGNORE = 0 - INFINITE = 0xffffffff - - WAIT_TIMEOUT = 258 - WAIT_ABANDONED = 0x00000080 - WAIT_OBJECT_0 = 0x00000000 - WAIT_FAILED = 0xFFFFFFFF - - CREATE_NEW_PROCESS_GROUP = 0x00000200 - CREATE_UNICODE_ENVIRONMENT = 0x00000400 - - PROCESS_TERMINATE = 1 - PROCESS_QUERY_INFORMATION = 0x00000400 - SYNCHRONIZE = 0x00100000 - - PAGE_READONLY = 0x02 - PAGE_READWRITE = 0x04 - PAGE_WRITECOPY = 0x08 - PAGE_EXECUTE_READ = 0x20 - PAGE_EXECUTE_READWRITE = 0x40 - PAGE_EXECUTE_WRITECOPY = 0x80 - - FILE_MAP_COPY = 0x01 - FILE_MAP_WRITE = 0x02 - FILE_MAP_READ = 0x04 - FILE_MAP_EXECUTE = 0x20 - - CTRL_C_EVENT = 0 - CTRL_BREAK_EVENT = 1 - - // Windows reserves errors >= 1<<29 for application use. - APPLICATION_ERROR = 1 << 29 -) - -const ( - // flags for CreateToolhelp32Snapshot - TH32CS_SNAPHEAPLIST = 0x01 - TH32CS_SNAPPROCESS = 0x02 - TH32CS_SNAPTHREAD = 0x04 - TH32CS_SNAPMODULE = 0x08 - TH32CS_SNAPMODULE32 = 0x10 - TH32CS_SNAPALL = TH32CS_SNAPHEAPLIST | TH32CS_SNAPMODULE | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD - TH32CS_INHERIT = 0x80000000 -) - -const ( - // filters for ReadDirectoryChangesW - FILE_NOTIFY_CHANGE_FILE_NAME = 0x001 - FILE_NOTIFY_CHANGE_DIR_NAME = 0x002 - FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x004 - FILE_NOTIFY_CHANGE_SIZE = 0x008 - FILE_NOTIFY_CHANGE_LAST_WRITE = 0x010 - FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x020 - FILE_NOTIFY_CHANGE_CREATION = 0x040 - FILE_NOTIFY_CHANGE_SECURITY = 0x100 -) - -const ( - // do not reorder - FILE_ACTION_ADDED = iota + 1 - FILE_ACTION_REMOVED - FILE_ACTION_MODIFIED - FILE_ACTION_RENAMED_OLD_NAME - FILE_ACTION_RENAMED_NEW_NAME -) - -const ( - // wincrypt.h - PROV_RSA_FULL = 1 - PROV_RSA_SIG = 2 - PROV_DSS = 3 - PROV_FORTEZZA = 4 - PROV_MS_EXCHANGE = 5 - PROV_SSL = 6 - PROV_RSA_SCHANNEL = 12 - PROV_DSS_DH = 13 - PROV_EC_ECDSA_SIG = 14 - PROV_EC_ECNRA_SIG = 15 - PROV_EC_ECDSA_FULL = 16 - PROV_EC_ECNRA_FULL = 17 - PROV_DH_SCHANNEL = 18 - PROV_SPYRUS_LYNKS = 20 - PROV_RNG = 21 - PROV_INTEL_SEC = 22 - PROV_REPLACE_OWF = 23 - PROV_RSA_AES = 24 - CRYPT_VERIFYCONTEXT = 0xF0000000 - CRYPT_NEWKEYSET = 0x00000008 - CRYPT_DELETEKEYSET = 0x00000010 - CRYPT_MACHINE_KEYSET = 0x00000020 - CRYPT_SILENT = 0x00000040 - CRYPT_DEFAULT_CONTAINER_OPTIONAL = 0x00000080 - - USAGE_MATCH_TYPE_AND = 0 - USAGE_MATCH_TYPE_OR = 1 - - X509_ASN_ENCODING = 0x00000001 - PKCS_7_ASN_ENCODING = 0x00010000 - - CERT_STORE_PROV_MEMORY = 2 - - CERT_STORE_ADD_ALWAYS = 4 - - CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004 - - CERT_TRUST_NO_ERROR = 0x00000000 - CERT_TRUST_IS_NOT_TIME_VALID = 0x00000001 - CERT_TRUST_IS_REVOKED = 0x00000004 - CERT_TRUST_IS_NOT_SIGNATURE_VALID = 0x00000008 - CERT_TRUST_IS_NOT_VALID_FOR_USAGE = 0x00000010 - CERT_TRUST_IS_UNTRUSTED_ROOT = 0x00000020 - CERT_TRUST_REVOCATION_STATUS_UNKNOWN = 0x00000040 - CERT_TRUST_IS_CYCLIC = 0x00000080 - CERT_TRUST_INVALID_EXTENSION = 0x00000100 - CERT_TRUST_INVALID_POLICY_CONSTRAINTS = 0x00000200 - CERT_TRUST_INVALID_BASIC_CONSTRAINTS = 0x00000400 - CERT_TRUST_INVALID_NAME_CONSTRAINTS = 0x00000800 - CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT = 0x00001000 - CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT = 0x00002000 - CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT = 0x00004000 - CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT = 0x00008000 - CERT_TRUST_IS_OFFLINE_REVOCATION = 0x01000000 - CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY = 0x02000000 - CERT_TRUST_IS_EXPLICIT_DISTRUST = 0x04000000 - CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT = 0x08000000 - - CERT_CHAIN_POLICY_BASE = 1 - CERT_CHAIN_POLICY_AUTHENTICODE = 2 - CERT_CHAIN_POLICY_AUTHENTICODE_TS = 3 - CERT_CHAIN_POLICY_SSL = 4 - CERT_CHAIN_POLICY_BASIC_CONSTRAINTS = 5 - CERT_CHAIN_POLICY_NT_AUTH = 6 - CERT_CHAIN_POLICY_MICROSOFT_ROOT = 7 - CERT_CHAIN_POLICY_EV = 8 - - CERT_E_EXPIRED = 0x800B0101 - CERT_E_ROLE = 0x800B0103 - CERT_E_PURPOSE = 0x800B0106 - CERT_E_UNTRUSTEDROOT = 0x800B0109 - CERT_E_CN_NO_MATCH = 0x800B010F - - AUTHTYPE_CLIENT = 1 - AUTHTYPE_SERVER = 2 -) - -var ( - OID_PKIX_KP_SERVER_AUTH = []byte("1.3.6.1.5.5.7.3.1\x00") - OID_SERVER_GATED_CRYPTO = []byte("1.3.6.1.4.1.311.10.3.3\x00") - OID_SGC_NETSCAPE = []byte("2.16.840.1.113730.4.1\x00") -) - -// Invented values to support what package os expects. -type Timeval struct { - Sec int32 - Usec int32 -} - -func (tv *Timeval) Nanoseconds() int64 { - return (int64(tv.Sec)*1e6 + int64(tv.Usec)) * 1e3 -} - -func NsecToTimeval(nsec int64) (tv Timeval) { - tv.Sec = int32(nsec / 1e9) - tv.Usec = int32(nsec % 1e9 / 1e3) - return -} - -type SecurityAttributes struct { - Length uint32 - SecurityDescriptor uintptr - InheritHandle uint32 -} - -type Overlapped struct { - Internal uintptr - InternalHigh uintptr - Offset uint32 - OffsetHigh uint32 - HEvent Handle -} - -type FileNotifyInformation struct { - NextEntryOffset uint32 - Action uint32 - FileNameLength uint32 - FileName uint16 -} - -type Filetime struct { - LowDateTime uint32 - HighDateTime uint32 -} - -// Nanoseconds returns Filetime ft in nanoseconds -// since Epoch (00:00:00 UTC, January 1, 1970). -func (ft *Filetime) Nanoseconds() int64 { - // 100-nanosecond intervals since January 1, 1601 - nsec := int64(ft.HighDateTime)<<32 + int64(ft.LowDateTime) - // change starting time to the Epoch (00:00:00 UTC, January 1, 1970) - nsec -= 116444736000000000 - // convert into nanoseconds - nsec *= 100 - return nsec -} - -func NsecToFiletime(nsec int64) (ft Filetime) { - // convert into 100-nanosecond - nsec /= 100 - // change starting time to January 1, 1601 - nsec += 116444736000000000 - // split into high / low - ft.LowDateTime = uint32(nsec & 0xffffffff) - ft.HighDateTime = uint32(nsec >> 32 & 0xffffffff) - return ft -} - -type Win32finddata struct { - FileAttributes uint32 - CreationTime Filetime - LastAccessTime Filetime - LastWriteTime Filetime - FileSizeHigh uint32 - FileSizeLow uint32 - Reserved0 uint32 - Reserved1 uint32 - FileName [MAX_PATH - 1]uint16 - AlternateFileName [13]uint16 -} - -// This is the actual system call structure. -// Win32finddata is what we committed to in Go 1. -type win32finddata1 struct { - FileAttributes uint32 - CreationTime Filetime - LastAccessTime Filetime - LastWriteTime Filetime - FileSizeHigh uint32 - FileSizeLow uint32 - Reserved0 uint32 - Reserved1 uint32 - FileName [MAX_PATH]uint16 - AlternateFileName [14]uint16 -} - -func copyFindData(dst *Win32finddata, src *win32finddata1) { - dst.FileAttributes = src.FileAttributes - dst.CreationTime = src.CreationTime - dst.LastAccessTime = src.LastAccessTime - dst.LastWriteTime = src.LastWriteTime - dst.FileSizeHigh = src.FileSizeHigh - dst.FileSizeLow = src.FileSizeLow - dst.Reserved0 = src.Reserved0 - dst.Reserved1 = src.Reserved1 - - // The src is 1 element bigger than dst, but it must be NUL. - copy(dst.FileName[:], src.FileName[:]) - copy(dst.AlternateFileName[:], src.AlternateFileName[:]) -} - -type ByHandleFileInformation struct { - FileAttributes uint32 - CreationTime Filetime - LastAccessTime Filetime - LastWriteTime Filetime - VolumeSerialNumber uint32 - FileSizeHigh uint32 - FileSizeLow uint32 - NumberOfLinks uint32 - FileIndexHigh uint32 - FileIndexLow uint32 -} - -const ( - GetFileExInfoStandard = 0 - GetFileExMaxInfoLevel = 1 -) - -type Win32FileAttributeData struct { - FileAttributes uint32 - CreationTime Filetime - LastAccessTime Filetime - LastWriteTime Filetime - FileSizeHigh uint32 - FileSizeLow uint32 -} - -// ShowWindow constants -const ( - // winuser.h - SW_HIDE = 0 - SW_NORMAL = 1 - SW_SHOWNORMAL = 1 - SW_SHOWMINIMIZED = 2 - SW_SHOWMAXIMIZED = 3 - SW_MAXIMIZE = 3 - SW_SHOWNOACTIVATE = 4 - SW_SHOW = 5 - SW_MINIMIZE = 6 - SW_SHOWMINNOACTIVE = 7 - SW_SHOWNA = 8 - SW_RESTORE = 9 - SW_SHOWDEFAULT = 10 - SW_FORCEMINIMIZE = 11 -) - -type StartupInfo struct { - Cb uint32 - _ *uint16 - Desktop *uint16 - Title *uint16 - X uint32 - Y uint32 - XSize uint32 - YSize uint32 - XCountChars uint32 - YCountChars uint32 - FillAttribute uint32 - Flags uint32 - ShowWindow uint16 - _ uint16 - _ *byte - StdInput Handle - StdOutput Handle - StdErr Handle -} - -type ProcessInformation struct { - Process Handle - Thread Handle - ProcessId uint32 - ThreadId uint32 -} - -type ProcessEntry32 struct { - Size uint32 - Usage uint32 - ProcessID uint32 - DefaultHeapID uintptr - ModuleID uint32 - Threads uint32 - ParentProcessID uint32 - PriClassBase int32 - Flags uint32 - ExeFile [MAX_PATH]uint16 -} - -type Systemtime struct { - Year uint16 - Month uint16 - DayOfWeek uint16 - Day uint16 - Hour uint16 - Minute uint16 - Second uint16 - Milliseconds uint16 -} - -type Timezoneinformation struct { - Bias int32 - StandardName [32]uint16 - StandardDate Systemtime - StandardBias int32 - DaylightName [32]uint16 - DaylightDate Systemtime - DaylightBias int32 -} - -// Socket related. - -const ( - AF_UNSPEC = 0 - AF_UNIX = 1 - AF_INET = 2 - AF_INET6 = 23 - AF_NETBIOS = 17 - - SOCK_STREAM = 1 - SOCK_DGRAM = 2 - SOCK_RAW = 3 - SOCK_SEQPACKET = 5 - - IPPROTO_IP = 0 - IPPROTO_IPV6 = 0x29 - IPPROTO_TCP = 6 - IPPROTO_UDP = 17 - - SOL_SOCKET = 0xffff - SO_REUSEADDR = 4 - SO_KEEPALIVE = 8 - SO_DONTROUTE = 16 - SO_BROADCAST = 32 - SO_LINGER = 128 - SO_RCVBUF = 0x1002 - SO_SNDBUF = 0x1001 - SO_UPDATE_ACCEPT_CONTEXT = 0x700b - SO_UPDATE_CONNECT_CONTEXT = 0x7010 - - IOC_OUT = 0x40000000 - IOC_IN = 0x80000000 - IOC_VENDOR = 0x18000000 - IOC_INOUT = IOC_IN | IOC_OUT - IOC_WS2 = 0x08000000 - SIO_GET_EXTENSION_FUNCTION_POINTER = IOC_INOUT | IOC_WS2 | 6 - SIO_KEEPALIVE_VALS = IOC_IN | IOC_VENDOR | 4 - SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12 - - // cf. http://support.microsoft.com/default.aspx?scid=kb;en-us;257460 - - IP_TOS = 0x3 - IP_TTL = 0x4 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_TTL = 0xa - IP_MULTICAST_LOOP = 0xb - IP_ADD_MEMBERSHIP = 0xc - IP_DROP_MEMBERSHIP = 0xd - - IPV6_V6ONLY = 0x1b - IPV6_UNICAST_HOPS = 0x4 - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_LOOP = 0xb - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - - SOMAXCONN = 0x7fffffff - - TCP_NODELAY = 1 - - SHUT_RD = 0 - SHUT_WR = 1 - SHUT_RDWR = 2 - - WSADESCRIPTION_LEN = 256 - WSASYS_STATUS_LEN = 128 -) - -type WSABuf struct { - Len uint32 - Buf *byte -} - -// Invented values to support what package os expects. -const ( - S_IFMT = 0x1f000 - S_IFIFO = 0x1000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFBLK = 0x6000 - S_IFREG = 0x8000 - S_IFLNK = 0xa000 - S_IFSOCK = 0xc000 - S_ISUID = 0x800 - S_ISGID = 0x400 - S_ISVTX = 0x200 - S_IRUSR = 0x100 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXUSR = 0x40 -) - -const ( - FILE_TYPE_CHAR = 0x0002 - FILE_TYPE_DISK = 0x0001 - FILE_TYPE_PIPE = 0x0003 - FILE_TYPE_REMOTE = 0x8000 - FILE_TYPE_UNKNOWN = 0x0000 -) - -type Hostent struct { - Name *byte - Aliases **byte - AddrType uint16 - Length uint16 - AddrList **byte -} - -type Protoent struct { - Name *byte - Aliases **byte - Proto uint16 -} - -const ( - DNS_TYPE_A = 0x0001 - DNS_TYPE_NS = 0x0002 - DNS_TYPE_MD = 0x0003 - DNS_TYPE_MF = 0x0004 - DNS_TYPE_CNAME = 0x0005 - DNS_TYPE_SOA = 0x0006 - DNS_TYPE_MB = 0x0007 - DNS_TYPE_MG = 0x0008 - DNS_TYPE_MR = 0x0009 - DNS_TYPE_NULL = 0x000a - DNS_TYPE_WKS = 0x000b - DNS_TYPE_PTR = 0x000c - DNS_TYPE_HINFO = 0x000d - DNS_TYPE_MINFO = 0x000e - DNS_TYPE_MX = 0x000f - DNS_TYPE_TEXT = 0x0010 - DNS_TYPE_RP = 0x0011 - DNS_TYPE_AFSDB = 0x0012 - DNS_TYPE_X25 = 0x0013 - DNS_TYPE_ISDN = 0x0014 - DNS_TYPE_RT = 0x0015 - DNS_TYPE_NSAP = 0x0016 - DNS_TYPE_NSAPPTR = 0x0017 - DNS_TYPE_SIG = 0x0018 - DNS_TYPE_KEY = 0x0019 - DNS_TYPE_PX = 0x001a - DNS_TYPE_GPOS = 0x001b - DNS_TYPE_AAAA = 0x001c - DNS_TYPE_LOC = 0x001d - DNS_TYPE_NXT = 0x001e - DNS_TYPE_EID = 0x001f - DNS_TYPE_NIMLOC = 0x0020 - DNS_TYPE_SRV = 0x0021 - DNS_TYPE_ATMA = 0x0022 - DNS_TYPE_NAPTR = 0x0023 - DNS_TYPE_KX = 0x0024 - DNS_TYPE_CERT = 0x0025 - DNS_TYPE_A6 = 0x0026 - DNS_TYPE_DNAME = 0x0027 - DNS_TYPE_SINK = 0x0028 - DNS_TYPE_OPT = 0x0029 - DNS_TYPE_DS = 0x002B - DNS_TYPE_RRSIG = 0x002E - DNS_TYPE_NSEC = 0x002F - DNS_TYPE_DNSKEY = 0x0030 - DNS_TYPE_DHCID = 0x0031 - DNS_TYPE_UINFO = 0x0064 - DNS_TYPE_UID = 0x0065 - DNS_TYPE_GID = 0x0066 - DNS_TYPE_UNSPEC = 0x0067 - DNS_TYPE_ADDRS = 0x00f8 - DNS_TYPE_TKEY = 0x00f9 - DNS_TYPE_TSIG = 0x00fa - DNS_TYPE_IXFR = 0x00fb - DNS_TYPE_AXFR = 0x00fc - DNS_TYPE_MAILB = 0x00fd - DNS_TYPE_MAILA = 0x00fe - DNS_TYPE_ALL = 0x00ff - DNS_TYPE_ANY = 0x00ff - DNS_TYPE_WINS = 0xff01 - DNS_TYPE_WINSR = 0xff02 - DNS_TYPE_NBSTAT = 0xff01 -) - -const ( - DNS_INFO_NO_RECORDS = 0x251D -) - -const ( - // flags inside DNSRecord.Dw - DnsSectionQuestion = 0x0000 - DnsSectionAnswer = 0x0001 - DnsSectionAuthority = 0x0002 - DnsSectionAdditional = 0x0003 -) - -type DNSSRVData struct { - Target *uint16 - Priority uint16 - Weight uint16 - Port uint16 - Pad uint16 -} - -type DNSPTRData struct { - Host *uint16 -} - -type DNSMXData struct { - NameExchange *uint16 - Preference uint16 - Pad uint16 -} - -type DNSTXTData struct { - StringCount uint16 - StringArray [1]*uint16 -} - -type DNSRecord struct { - Next *DNSRecord - Name *uint16 - Type uint16 - Length uint16 - Dw uint32 - Ttl uint32 - Reserved uint32 - Data [40]byte -} - -const ( - TF_DISCONNECT = 1 - TF_REUSE_SOCKET = 2 - TF_WRITE_BEHIND = 4 - TF_USE_DEFAULT_WORKER = 0 - TF_USE_SYSTEM_THREAD = 16 - TF_USE_KERNEL_APC = 32 -) - -type TransmitFileBuffers struct { - Head uintptr - HeadLength uint32 - Tail uintptr - TailLength uint32 -} - -const ( - IFF_UP = 1 - IFF_BROADCAST = 2 - IFF_LOOPBACK = 4 - IFF_POINTTOPOINT = 8 - IFF_MULTICAST = 16 -) - -const SIO_GET_INTERFACE_LIST = 0x4004747F - -// TODO(mattn): SockaddrGen is union of sockaddr/sockaddr_in/sockaddr_in6_old. -// will be fixed to change variable type as suitable. - -type SockaddrGen [24]byte - -type InterfaceInfo struct { - Flags uint32 - Address SockaddrGen - BroadcastAddress SockaddrGen - Netmask SockaddrGen -} - -type IpAddressString struct { - String [16]byte -} - -type IpMaskString IpAddressString - -type IpAddrString struct { - Next *IpAddrString - IpAddress IpAddressString - IpMask IpMaskString - Context uint32 -} - -const MAX_ADAPTER_NAME_LENGTH = 256 -const MAX_ADAPTER_DESCRIPTION_LENGTH = 128 -const MAX_ADAPTER_ADDRESS_LENGTH = 8 - -type IpAdapterInfo struct { - Next *IpAdapterInfo - ComboIndex uint32 - AdapterName [MAX_ADAPTER_NAME_LENGTH + 4]byte - Description [MAX_ADAPTER_DESCRIPTION_LENGTH + 4]byte - AddressLength uint32 - Address [MAX_ADAPTER_ADDRESS_LENGTH]byte - Index uint32 - Type uint32 - DhcpEnabled uint32 - CurrentIpAddress *IpAddrString - IpAddressList IpAddrString - GatewayList IpAddrString - DhcpServer IpAddrString - HaveWins bool - PrimaryWinsServer IpAddrString - SecondaryWinsServer IpAddrString - LeaseObtained int64 - LeaseExpires int64 -} - -const MAXLEN_PHYSADDR = 8 -const MAX_INTERFACE_NAME_LEN = 256 -const MAXLEN_IFDESCR = 256 - -type MibIfRow struct { - Name [MAX_INTERFACE_NAME_LEN]uint16 - Index uint32 - Type uint32 - Mtu uint32 - Speed uint32 - PhysAddrLen uint32 - PhysAddr [MAXLEN_PHYSADDR]byte - AdminStatus uint32 - OperStatus uint32 - LastChange uint32 - InOctets uint32 - InUcastPkts uint32 - InNUcastPkts uint32 - InDiscards uint32 - InErrors uint32 - InUnknownProtos uint32 - OutOctets uint32 - OutUcastPkts uint32 - OutNUcastPkts uint32 - OutDiscards uint32 - OutErrors uint32 - OutQLen uint32 - DescrLen uint32 - Descr [MAXLEN_IFDESCR]byte -} - -type CertContext struct { - EncodingType uint32 - EncodedCert *byte - Length uint32 - CertInfo uintptr - Store Handle -} - -type CertChainContext struct { - Size uint32 - TrustStatus CertTrustStatus - ChainCount uint32 - Chains **CertSimpleChain - LowerQualityChainCount uint32 - LowerQualityChains **CertChainContext - HasRevocationFreshnessTime uint32 - RevocationFreshnessTime uint32 -} - -type CertSimpleChain struct { - Size uint32 - TrustStatus CertTrustStatus - NumElements uint32 - Elements **CertChainElement - TrustListInfo uintptr - HasRevocationFreshnessTime uint32 - RevocationFreshnessTime uint32 -} - -type CertChainElement struct { - Size uint32 - CertContext *CertContext - TrustStatus CertTrustStatus - RevocationInfo *CertRevocationInfo - IssuanceUsage *CertEnhKeyUsage - ApplicationUsage *CertEnhKeyUsage - ExtendedErrorInfo *uint16 -} - -type CertRevocationInfo struct { - Size uint32 - RevocationResult uint32 - RevocationOid *byte - OidSpecificInfo uintptr - HasFreshnessTime uint32 - FreshnessTime uint32 - CrlInfo uintptr // *CertRevocationCrlInfo -} - -type CertTrustStatus struct { - ErrorStatus uint32 - InfoStatus uint32 -} - -type CertUsageMatch struct { - Type uint32 - Usage CertEnhKeyUsage -} - -type CertEnhKeyUsage struct { - Length uint32 - UsageIdentifiers **byte -} - -type CertChainPara struct { - Size uint32 - RequestedUsage CertUsageMatch - RequstedIssuancePolicy CertUsageMatch - URLRetrievalTimeout uint32 - CheckRevocationFreshnessTime uint32 - RevocationFreshnessTime uint32 - CacheResync *Filetime -} - -type CertChainPolicyPara struct { - Size uint32 - Flags uint32 - ExtraPolicyPara uintptr -} - -type SSLExtraCertChainPolicyPara struct { - Size uint32 - AuthType uint32 - Checks uint32 - ServerName *uint16 -} - -type CertChainPolicyStatus struct { - Size uint32 - Error uint32 - ChainIndex uint32 - ElementIndex uint32 - ExtraPolicyStatus uintptr -} - -const ( - // do not reorder - HKEY_CLASSES_ROOT = 0x80000000 + iota - HKEY_CURRENT_USER - HKEY_LOCAL_MACHINE - HKEY_USERS - HKEY_PERFORMANCE_DATA - HKEY_CURRENT_CONFIG - HKEY_DYN_DATA - - KEY_QUERY_VALUE = 1 - KEY_SET_VALUE = 2 - KEY_CREATE_SUB_KEY = 4 - KEY_ENUMERATE_SUB_KEYS = 8 - KEY_NOTIFY = 16 - KEY_CREATE_LINK = 32 - KEY_WRITE = 0x20006 - KEY_EXECUTE = 0x20019 - KEY_READ = 0x20019 - KEY_WOW64_64KEY = 0x0100 - KEY_WOW64_32KEY = 0x0200 - KEY_ALL_ACCESS = 0xf003f -) - -const ( - // do not reorder - REG_NONE = iota - REG_SZ - REG_EXPAND_SZ - REG_BINARY - REG_DWORD_LITTLE_ENDIAN - REG_DWORD_BIG_ENDIAN - REG_LINK - REG_MULTI_SZ - REG_RESOURCE_LIST - REG_FULL_RESOURCE_DESCRIPTOR - REG_RESOURCE_REQUIREMENTS_LIST - REG_QWORD_LITTLE_ENDIAN - REG_DWORD = REG_DWORD_LITTLE_ENDIAN - REG_QWORD = REG_QWORD_LITTLE_ENDIAN -) - -type AddrinfoW struct { - Flags int32 - Family int32 - Socktype int32 - Protocol int32 - Addrlen uintptr - Canonname *uint16 - Addr uintptr - Next *AddrinfoW -} - -const ( - AI_PASSIVE = 1 - AI_CANONNAME = 2 - AI_NUMERICHOST = 4 -) - -type GUID struct { - Data1 uint32 - Data2 uint16 - Data3 uint16 - Data4 [8]byte -} - -var WSAID_CONNECTEX = GUID{ - 0x25a207b9, - 0xddf3, - 0x4660, - [8]byte{0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e}, -} - -const ( - FILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1 - FILE_SKIP_SET_EVENT_ON_HANDLE = 2 -) - -const ( - WSAPROTOCOL_LEN = 255 - MAX_PROTOCOL_CHAIN = 7 - BASE_PROTOCOL = 1 - LAYERED_PROTOCOL = 0 - - XP1_CONNECTIONLESS = 0x00000001 - XP1_GUARANTEED_DELIVERY = 0x00000002 - XP1_GUARANTEED_ORDER = 0x00000004 - XP1_MESSAGE_ORIENTED = 0x00000008 - XP1_PSEUDO_STREAM = 0x00000010 - XP1_GRACEFUL_CLOSE = 0x00000020 - XP1_EXPEDITED_DATA = 0x00000040 - XP1_CONNECT_DATA = 0x00000080 - XP1_DISCONNECT_DATA = 0x00000100 - XP1_SUPPORT_BROADCAST = 0x00000200 - XP1_SUPPORT_MULTIPOINT = 0x00000400 - XP1_MULTIPOINT_CONTROL_PLANE = 0x00000800 - XP1_MULTIPOINT_DATA_PLANE = 0x00001000 - XP1_QOS_SUPPORTED = 0x00002000 - XP1_UNI_SEND = 0x00008000 - XP1_UNI_RECV = 0x00010000 - XP1_IFS_HANDLES = 0x00020000 - XP1_PARTIAL_MESSAGE = 0x00040000 - XP1_SAN_SUPPORT_SDP = 0x00080000 - - PFL_MULTIPLE_PROTO_ENTRIES = 0x00000001 - PFL_RECOMMENDED_PROTO_ENTRY = 0x00000002 - PFL_HIDDEN = 0x00000004 - PFL_MATCHES_PROTOCOL_ZERO = 0x00000008 - PFL_NETWORKDIRECT_PROVIDER = 0x00000010 -) - -type WSAProtocolInfo struct { - ServiceFlags1 uint32 - ServiceFlags2 uint32 - ServiceFlags3 uint32 - ServiceFlags4 uint32 - ProviderFlags uint32 - ProviderId GUID - CatalogEntryId uint32 - ProtocolChain WSAProtocolChain - Version int32 - AddressFamily int32 - MaxSockAddr int32 - MinSockAddr int32 - SocketType int32 - Protocol int32 - ProtocolMaxOffset int32 - NetworkByteOrder int32 - SecurityScheme int32 - MessageSize uint32 - ProviderReserved uint32 - ProtocolName [WSAPROTOCOL_LEN + 1]uint16 -} - -type WSAProtocolChain struct { - ChainLen int32 - ChainEntries [MAX_PROTOCOL_CHAIN]uint32 -} - -type TCPKeepalive struct { - OnOff uint32 - Time uint32 - Interval uint32 -} - -type symbolicLinkReparseBuffer struct { - SubstituteNameOffset uint16 - SubstituteNameLength uint16 - PrintNameOffset uint16 - PrintNameLength uint16 - Flags uint32 - PathBuffer [1]uint16 -} - -type mountPointReparseBuffer struct { - SubstituteNameOffset uint16 - SubstituteNameLength uint16 - PrintNameOffset uint16 - PrintNameLength uint16 - PathBuffer [1]uint16 -} - -type reparseDataBuffer struct { - ReparseTag uint32 - ReparseDataLength uint16 - Reserved uint16 - - // GenericReparseBuffer - reparseBuffer byte -} - -const ( - FSCTL_GET_REPARSE_POINT = 0x900A8 - MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16 * 1024 - IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 - IO_REPARSE_TAG_SYMLINK = 0xA000000C - SYMBOLIC_LINK_FLAG_DIRECTORY = 0x1 -) - -const ( - ComputerNameNetBIOS = 0 - ComputerNameDnsHostname = 1 - ComputerNameDnsDomain = 2 - ComputerNameDnsFullyQualified = 3 - ComputerNamePhysicalNetBIOS = 4 - ComputerNamePhysicalDnsHostname = 5 - ComputerNamePhysicalDnsDomain = 6 - ComputerNamePhysicalDnsFullyQualified = 7 - ComputerNameMax = 8 -) diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/ztypes_windows_386.go b/Godeps/_workspace/src/golang.org/x/sys/windows/ztypes_windows_386.go deleted file mode 100644 index 10f33be..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/ztypes_windows_386.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package windows - -type WSAData struct { - Version uint16 - HighVersion uint16 - Description [WSADESCRIPTION_LEN + 1]byte - SystemStatus [WSASYS_STATUS_LEN + 1]byte - MaxSockets uint16 - MaxUdpDg uint16 - VendorInfo *byte -} - -type Servent struct { - Name *byte - Aliases **byte - Port uint16 - Proto *byte -} diff --git a/Godeps/_workspace/src/golang.org/x/sys/windows/ztypes_windows_amd64.go b/Godeps/_workspace/src/golang.org/x/sys/windows/ztypes_windows_amd64.go deleted file mode 100644 index 3f272c2..0000000 --- a/Godeps/_workspace/src/golang.org/x/sys/windows/ztypes_windows_amd64.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package windows - -type WSAData struct { - Version uint16 - HighVersion uint16 - MaxSockets uint16 - MaxUdpDg uint16 - VendorInfo *byte - Description [WSADESCRIPTION_LEN + 1]byte - SystemStatus [WSASYS_STATUS_LEN + 1]byte -} - -type Servent struct { - Name *byte - Aliases **byte - Proto *byte - Port uint16 -} diff --git a/README.md b/README.md index b7c2c43..3306b36 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ The `servedMssqlBindingHostname` and `servedMssqlBindingPort` properties need to `logLevel` will set the logging level. Accepted levels: "debug", "info", "error", and "fatal". -The `brokerGoSqlDriver` and `brokerMssqlConnection` are settings that the broker uses to connect to the mssql instance. `brokerGoSqlDriver` can be "odbc" (recommended https://code.google.com/p/odbc/) or "mssql" (experimental https://github.com/denisenkom/go-mssqldb). `brokerMssqlConnection` is a key-value JSON object that is +The `brokerGoSqlDriver` and `brokerMssqlConnection` are settings that the broker uses to connect to the mssql instance. `brokerGoSqlDriver` can be "odbc" (recommended https://github.com/alexbrainman/odbc/) or "mssql" (experimental https://github.com/denisenkom/go-mssqldb). `brokerMssqlConnection` is a key-value JSON object that is converted into a connection string (e.g. {"server":"localhost","port":1433} is converted to "server=localhost;port=1433") consumed by ODBC or mssql go library. Example for a local trusted `brokerMssqlConnection` with ODBC driver: { @@ -94,8 +94,8 @@ go get -u -v go get github.com/cloudfoundry-incubator/cf-mssql-broker/... godep update ... # Or to update a specific package (e.g. odbc package): -go get -u -v code.google.com/p/odbc -godep update code.google.com/p/odbc +go get -u -v github.com/alexbrainman/odbc +godep update github.com/alexbrainman/odbc git add Godeps/* ``` @@ -229,4 +229,4 @@ Using the Odbc provider: Using OleDb provider: ```xml -``` \ No newline at end of file +``` diff --git a/provisioner/go_sql_odbc_driver.go b/provisioner/go_sql_odbc_driver.go index d71084d..22e0876 100644 --- a/provisioner/go_sql_odbc_driver.go +++ b/provisioner/go_sql_odbc_driver.go @@ -14,5 +14,5 @@ package provisioner import ( - _ "code.google.com/p/odbc" + _ "github.com/alexbrainman/odbc" )