See More

diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 00000000000000..c29ea07ce66841 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,4 @@ +lib/punycode.js +test/fixtures +test/**/node_modules +test/parallel/test-fs-non-number-arguments-throw.js diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 00000000000000..e023327fbb7d00 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,96 @@ +env: + node: true + +# enable ECMAScript features +ecmaFeatures: + blockBindings: true + templateStrings: true + octalLiterals: true + binaryLiterals: true + generators: true + forOf: true + +rules: + # Possible Errors + # list: https://github.com/eslint/eslint/tree/master/docs/rules#possible-errors + ## check debugger sentence + no-debugger: 2 + ## check duplicate arguments + no-dupe-args: 2 + ## check duplicate object keys + no-dupe-keys: 2 + ## check duplicate switch-case + no-duplicate-case: 2 + ## disallow assignment of exceptional params + no-ex-assign: 2 + ## disallow use of reserved words as keys like enum, class + no-reserved-keys: 2 + ## disallow unreachable code + no-unreachable: 2 + ## require valid typeof compared string like typeof foo === 'strnig' + valid-typeof: 2 + + # Best Practices + # list: https://github.com/eslint/eslint/tree/master/docs/rules#best-practices + ## require falls through comment on switch-case + no-fallthrough: 2 + + # Stylistic Issues + # list: https://github.com/eslint/eslint/tree/master/docs/rules#stylistic-issues + ## use single quote, we can use double quote when escape chars + quotes: + - 2 + - "single" + - "avoid-escape" + ## 2 space indentation + indent: + - 2 + - 2 + ## add space after comma + ## set to 'warn' because of https://github.com/eslint/eslint/issues/2408 + comma-spacing: 1 + ## put semi-colon + semi: 2 + ## require spaces operator like var sum = 1 + 1; + space-infix-ops: 2 + ## require spaces return, throw, case + space-return-throw-case: 2 + ## no space before function, eg. 'function()' + space-before-function-paren: [2, "never"] + ## require space before blocks, eg 'function() {' + space-before-blocks: [2, "always"] + ## require parens for Constructor + new-parens: 2 + ## max 80 length + max-len: + - 2 + - 80 + - 2 + + # Strict Mode + # list: https://github.com/eslint/eslint/tree/master/docs/rules#strict-mode + ## 'use strict' on top + strict: + - 2 + - "global" + +# Global scoped method and vars +globals: + DTRACE_HTTP_CLIENT_REQUEST: true + LTTNG_HTTP_CLIENT_REQUEST: true + COUNTER_HTTP_CLIENT_REQUEST: true + DTRACE_HTTP_CLIENT_RESPONSE: true + LTTNG_HTTP_CLIENT_RESPONSE: true + COUNTER_HTTP_CLIENT_RESPONSE: true + DTRACE_HTTP_SERVER_REQUEST: true + LTTNG_HTTP_SERVER_REQUEST: true + COUNTER_HTTP_SERVER_REQUEST: true + DTRACE_HTTP_SERVER_RESPONSE: true + LTTNG_HTTP_SERVER_RESPONSE: true + COUNTER_HTTP_SERVER_RESPONSE: true + DTRACE_NET_STREAM_END: true + LTTNG_NET_STREAM_END: true + COUNTER_NET_SERVER_CONNECTION_CLOSE: true + DTRACE_NET_SERVER_CONNECTION: true + LTTNG_NET_SERVER_CONNECTION: true + COUNTER_NET_SERVER_CONNECTION: true diff --git a/.gitignore b/.gitignore index 19fb3840039160..ebb9a7bc56375c 100644 --- a/.gitignore +++ b/.gitignore @@ -76,3 +76,7 @@ deps/zlib/zlib.target.mk tools/faketime icu_config.gypi test.tap + +# Xcode workspaces and project folders +*.xcodeproj +*.xcworkspace diff --git a/Makefile b/Makefile index 8fc67d604e91b0..94f130f5fb3287 100644 --- a/Makefile +++ b/Makefile @@ -138,19 +138,7 @@ test-debugger: all $(PYTHON) tools/test.py debugger test-npm: $(NODE_EXE) - rm -rf npm-cache npm-tmp npm-prefix - mkdir npm-cache npm-tmp npm-prefix - cd deps/npm ; npm_config_cache="$(shell pwd)/npm-cache" \ - npm_config_prefix="$(shell pwd)/npm-prefix" \ - npm_config_tmp="$(shell pwd)/npm-tmp" \ - ../../$(NODE_EXE) cli.js install --ignore-scripts - cd deps/npm ; npm_config_cache="$(shell pwd)/npm-cache" \ - npm_config_prefix="$(shell pwd)/npm-prefix" \ - npm_config_tmp="$(shell pwd)/npm-tmp" \ - ../../$(NODE_EXE) cli.js run-script test-all && \ - ../../$(NODE_EXE) cli.js prune --prod && \ - cd ../.. && \ - rm -rf npm-cache npm-tmp npm-prefix + NODE_EXE=$(NODE_EXE) tools/test-npm.sh test-npm-publish: $(NODE_EXE) npm_package_config_publishtest=true ./$(NODE_EXE) deps/npm/test/run.js @@ -386,11 +374,8 @@ bench-idle: sleep 1 ./$(NODE_EXE) benchmark/idle_clients.js & -jslintfix: - PYTHONPATH=tools/closure_linter/:tools/gflags/ $(PYTHON) tools/closure_linter/closure_linter/fixjsstyle.py --strict --nojsdoc -r lib/ -r src/ --exclude_files lib/punycode.js - jslint: - PYTHONPATH=tools/closure_linter/:tools/gflags/ $(PYTHON) tools/closure_linter/closure_linter/gjslint.py --unix_mode --strict --nojsdoc -r lib/ -r src/ --exclude_files lib/punycode.js + ./$(NODE_EXE) tools/eslint/bin/eslint.js src lib test --reset --quiet CPPLINT_EXCLUDE ?= CPPLINT_EXCLUDE += src/node_lttng.cc diff --git a/benchmark/misc/next-tick-breadth-args.js b/benchmark/misc/next-tick-breadth-args.js new file mode 100644 index 00000000000000..e617fcfc824f7f --- /dev/null +++ b/benchmark/misc/next-tick-breadth-args.js @@ -0,0 +1,37 @@ +'use strict'; + +var common = require('../common.js'); +var bench = common.createBenchmark(main, { + millions: [2] +}); + +function main(conf) { + var N = +conf.millions * 1e6; + var n = 0; + + function cb1(arg1) { + n++; + if (n === N) + bench.end(n / 1e6); + } + function cb2(arg1, arg2) { + n++; + if (n === N) + bench.end(n / 1e6); + } + function cb3(arg1, arg2, arg3) { + n++; + if (n === N) + bench.end(n / 1e6); + } + + bench.start(); + for (var i = 0; i < N; i++) { + if (i % 3 === 0) + process.nextTick(cb3, 512, true, null); + else if (i % 2 === 0) + process.nextTick(cb2, false, 5.1); + else + process.nextTick(cb1, 0); + } +} diff --git a/benchmark/misc/next-tick-depth-args.js b/benchmark/misc/next-tick-depth-args.js new file mode 100644 index 00000000000000..066b4837856f60 --- /dev/null +++ b/benchmark/misc/next-tick-depth-args.js @@ -0,0 +1,48 @@ +'use strict'; + +var common = require('../common.js'); +var bench = common.createBenchmark(main, { + millions: [2] +}); + +process.maxTickDepth = Infinity; + +function main(conf) { + var n = +conf.millions * 1e6; + + function cb3(arg1, arg2, arg3) { + if (--n) { + if (n % 3 === 0) + process.nextTick(cb3, 512, true, null); + else if (n % 2 === 0) + process.nextTick(cb2, false, 5.1); + else + process.nextTick(cb1, 0); + } else + bench.end(+conf.millions); + } + function cb2(arg1, arg2) { + if (--n) { + if (n % 3 === 0) + process.nextTick(cb3, 512, true, null); + else if (n % 2 === 0) + process.nextTick(cb2, false, 5.1); + else + process.nextTick(cb1, 0); + } else + bench.end(+conf.millions); + } + function cb1(arg1) { + if (--n) { + if (n % 3 === 0) + process.nextTick(cb3, 512, true, null); + else if (n % 2 === 0) + process.nextTick(cb2, false, 5.1); + else + process.nextTick(cb1, 0); + } else + bench.end(+conf.millions); + } + bench.start(); + process.nextTick(cb1, true); +} diff --git a/configure b/configure index 8a19a5313cd67e..4a30973a3720ab 100755 --- a/configure +++ b/configure @@ -31,6 +31,16 @@ valid_arm_float_abi = ('soft', 'softfp', 'hard') valid_mips_arch = ('loongson', 'r1', 'r2', 'r6', 'rx') valid_mips_fpu = ('fp32', 'fp64', 'fpxx') valid_mips_float_abi = ('soft', 'hard') +valid_intl_modes = ('none', 'small-icu', 'full-icu', 'system-icu') + +# create option groups +shared_optgroup = optparse.OptionGroup(parser, "Shared libraries", + "Flags that allows you to control whether you want to build against " + "built-in dependencies or its shared representations. If necessary, " + "provide multiple libraries with comma.") +intl_optgroup = optparse.OptionGroup(parser, "Internationalization", + "Flags that lets you enable i18n features in io.js as well as which " + "library you want to build against.") # Options should be in alphabetical order but keep --prefix at the top, # that's arguably the one people will be looking for most. @@ -78,90 +88,92 @@ parser.add_option("--openssl-no-asm", dest="openssl_no_asm", help="Do not build optimized assembly for OpenSSL") -parser.add_option('--shared-http-parser', +shared_optgroup.add_option('--shared-http-parser', action='store_true', dest='shared_http_parser', help='link to a shared http_parser DLL instead of static linking') -parser.add_option('--shared-http-parser-includes', +shared_optgroup.add_option('--shared-http-parser-includes', action='store', dest='shared_http_parser_includes', help='directory containing http_parser header files') -parser.add_option('--shared-http-parser-libname', +shared_optgroup.add_option('--shared-http-parser-libname', action='store', dest='shared_http_parser_libname', default='http_parser', help='alternative lib name to link to [default: %default]') -parser.add_option('--shared-http-parser-libpath', +shared_optgroup.add_option('--shared-http-parser-libpath', action='store', dest='shared_http_parser_libpath', help='a directory to search for the shared http_parser DLL') -parser.add_option('--shared-libuv', +shared_optgroup.add_option('--shared-libuv', action='store_true', dest='shared_libuv', help='link to a shared libuv DLL instead of static linking') -parser.add_option('--shared-libuv-includes', +shared_optgroup.add_option('--shared-libuv-includes', action='store', dest='shared_libuv_includes', help='directory containing libuv header files') -parser.add_option('--shared-libuv-libname', +shared_optgroup.add_option('--shared-libuv-libname', action='store', dest='shared_libuv_libname', default='uv', help='alternative lib name to link to [default: %default]') -parser.add_option('--shared-libuv-libpath', +shared_optgroup.add_option('--shared-libuv-libpath', action='store', dest='shared_libuv_libpath', help='a directory to search for the shared libuv DLL') -parser.add_option('--shared-openssl', +shared_optgroup.add_option('--shared-openssl', action='store_true', dest='shared_openssl', help='link to a shared OpenSSl DLL instead of static linking') -parser.add_option('--shared-openssl-includes', +shared_optgroup.add_option('--shared-openssl-includes', action='store', dest='shared_openssl_includes', help='directory containing OpenSSL header files') -parser.add_option('--shared-openssl-libname', +shared_optgroup.add_option('--shared-openssl-libname', action='store', dest='shared_openssl_libname', default='crypto,ssl', help='alternative lib name to link to [default: %default]') -parser.add_option('--shared-openssl-libpath', +shared_optgroup.add_option('--shared-openssl-libpath', action='store', dest='shared_openssl_libpath', help='a directory to search for the shared OpenSSL DLLs') -parser.add_option('--shared-zlib', +shared_optgroup.add_option('--shared-zlib', action='store_true', dest='shared_zlib', help='link to a shared zlib DLL instead of static linking') -parser.add_option('--shared-zlib-includes', +shared_optgroup.add_option('--shared-zlib-includes', action='store', dest='shared_zlib_includes', help='directory containing zlib header files') -parser.add_option('--shared-zlib-libname', +shared_optgroup.add_option('--shared-zlib-libname', action='store', dest='shared_zlib_libname', default='z', help='alternative lib name to link to [default: %default]') -parser.add_option('--shared-zlib-libpath', +shared_optgroup.add_option('--shared-zlib-libpath', action='store', dest='shared_zlib_libpath', help='a directory to search for the shared zlib DLL') +parser.add_option_group(shared_optgroup) + # TODO document when we've decided on what the tracing API and its options will # look like parser.add_option('--systemtap-includes', @@ -225,33 +237,38 @@ parser.add_option('--with-etw', dest='with_etw', help='build with ETW (default is true on Windows)') -parser.add_option('--download', +intl_optgroup.add_option('--with-intl', action='store', - dest='download_list', - help=nodedownload.help()) + dest='with_intl', + default='none', + choices=valid_intl_modes, + help='Intl mode (valid choices: {0}) [default: %default]'.format( + ', '.join(valid_intl_modes))) -parser.add_option('--with-icu-path', +intl_optgroup.add_option('--with-icu-path', action='store', dest='with_icu_path', help='Path to icu.gyp (ICU i18n, Chromium version only.)') -parser.add_option('--with-icu-locales', +intl_optgroup.add_option('--with-icu-locales', action='store', dest='with_icu_locales', default='root,en', help='Comma-separated list of locales for "small-icu". "root" is assumed. ' '[default: %default]') -parser.add_option('--with-intl', - action='store', - dest='with_intl', - help='Intl mode: none, full-icu, small-icu [default: none]') - -parser.add_option('--with-icu-source', +intl_optgroup.add_option('--with-icu-source', action='store', dest='with_icu_source', help='Intl mode: optional local path to icu/ dir, or path/URL of icu source archive.') +intl_optgroup.add_option('--download', + action='store', + dest='download_list', + help=nodedownload.help()) + +parser.add_option_group(intl_optgroup) + parser.add_option('--with-perfctr', action='store_true', dest='with_perfctr', @@ -277,15 +294,15 @@ parser.add_option('--without-perfctr', dest='without_perfctr', help='build without performance counters') +# Dummy option for backwards compatibility parser.add_option('--with-snapshot', action='store_true', - dest='with_snapshot', + dest='unused_with_snapshot', help=optparse.SUPPRESS_HELP) -# Dummy option for backwards compatibility. parser.add_option('--without-snapshot', action='store_true', - dest='unused_without_snapshot', + dest='without_snapshot', help=optparse.SUPPRESS_HELP) parser.add_option('--without-ssl', @@ -326,17 +343,28 @@ def b(value): def pkg_config(pkg): - cmd = os.popen('pkg-config --libs %s' % pkg, 'r') - libs = cmd.readline().strip() - ret = cmd.close() - if (ret): return None - - cmd = os.popen('pkg-config --cflags %s' % pkg, 'r') - cflags = cmd.readline().strip() - ret = cmd.close() - if (ret): return None - - return (libs, cflags) + pkg_config = os.environ.get('PKG_CONFIG', 'pkg-config') + args = '--silence-errors' + retval = () + for flag in ['--libs-only-l', '--cflags-only-I', '--libs-only-L']: + try: + val = subprocess.check_output([pkg_config, args, flag, pkg]) + # check_output returns bytes + val = val.encode().strip().rstrip('\n') + except subprocess.CalledProcessError: + # most likely missing a .pc-file + val = None + except OSError: + # no pkg-config/pkgconf installed + return (None, None, None) + retval += (val,) + return retval + + +def format_libraries(list): + """Returns string of space separated libraries""" + libraries = list.split(',') + return ' '.join('-l{0}'.format(i) for i in libraries) def try_check_compiler(cc, lang): @@ -562,10 +590,6 @@ def configure_arm(o): o['variables']['arm_fpu'] = 'vfpv3' o['variables']['arm_version'] = '7' - # Print warning when snapshot is enabled and building on armv6 - if is_arch_armv6() and options.with_snapshot: - warn('when building on ARMv6, don\'t use --with-snapshot') - def configure_mips(o): can_use_fpu_instructions = (options.mips_float_abi != 'soft') @@ -587,10 +611,10 @@ def configure_node(o): o['variables']['host_arch'] = host_arch o['variables']['target_arch'] = target_arch - if target_arch != host_arch and options.with_snapshot: - o['variables']['want_separate_host_toolset'] = 1 - else: - o['variables']['want_separate_host_toolset'] = 0 + cross_compiling = target_arch != host_arch + want_snapshots = not options.without_snapshot + o['variables']['want_separate_host_toolset'] = int( + cross_compiling and want_snapshots) if target_arch == 'arm': configure_arm(o) @@ -655,40 +679,30 @@ def configure_node(o): o['variables']['node_target_type'] = 'static_library' -def configure_libz(o): - o['variables']['node_shared_zlib'] = b(options.shared_zlib) - - if options.shared_zlib: - o['libraries'] += ['-l%s' % options.shared_zlib_libname] - if options.shared_zlib_libpath: - o['libraries'] += ['-L%s' % options.shared_zlib_libpath] - if options.shared_zlib_includes: - o['include_dirs'] += [options.shared_zlib_includes] - - -def configure_http_parser(o): - o['variables']['node_shared_http_parser'] = b(options.shared_http_parser) - - if options.shared_http_parser: - o['libraries'] += ['-l%s' % options.shared_http_parser_libname] - if options.shared_http_parser_libpath: - o['libraries'] += ['-L%s' % options.shared_http_parser_libpath] - if options.shared_http_parser_includes: - o['include_dirs'] += [options.shared_http_parser_includes] - - -def configure_libuv(o): - o['variables']['node_shared_libuv'] = b(options.shared_libuv) - - if options.shared_libuv: - o['libraries'] += ['-l%s' % options.shared_libuv_libname] - if options.shared_libuv_libpath: - o['libraries'] += ['-L%s' % options.shared_libuv_libpath] - else: - o['variables']['uv_library'] = 'static_library' - - if options.shared_libuv_includes: - o['include_dirs'] += [options.shared_libuv_includes] +def configure_library(lib, output): + shared_lib = 'shared_' + lib + output['variables']['node_' + shared_lib] = b(getattr(options, shared_lib)) + + if getattr(options, shared_lib): + default_cflags = getattr(options, shared_lib + '_includes') + default_lib = format_libraries(getattr(options, shared_lib + '_libname')) + default_libpath = getattr(options, shared_lib + '_libpath') + if default_libpath: + default_libpath = '-L' + default_libpath + (pkg_libs, pkg_cflags, pkg_libpath) = pkg_config(lib) + cflags = pkg_cflags.split('-I') if pkg_cflags else default_cflags + libs = pkg_libs if pkg_libs else default_lib + libpath = pkg_libpath if pkg_libpath else default_libpath + + # libpath needs to be provided ahead libraries + if libpath: + output['libraries'] += [libpath] + if libs: + # libs passed to the linker cannot contain spaces. + # (libpath on the other hand can) + output['libraries'] += libs.split() + if cflags: + output['include_dirs'] += [cflags] def configure_v8(o): @@ -696,30 +710,16 @@ def configure_v8(o): o['variables']['v8_no_strict_aliasing'] = 1 # Work around compiler bugs. o['variables']['v8_optimized_debug'] = 0 # Compile with -O0 in debug builds. o['variables']['v8_random_seed'] = 0 # Use a random seed for hash tables. - o['variables']['v8_use_snapshot'] = b(options.with_snapshot) + o['variables']['v8_use_snapshot'] = 0 if options.without_snapshot else 1 def configure_openssl(o): o['variables']['node_use_openssl'] = b(not options.without_ssl) o['variables']['node_shared_openssl'] = b(options.shared_openssl) - o['variables']['openssl_no_asm'] = ( - 1 if options.openssl_no_asm else 0) + o['variables']['openssl_no_asm'] = 1 if options.openssl_no_asm else 0 if options.without_ssl: return - - if options.shared_openssl: - (libs, cflags) = pkg_config('openssl') or ('-lssl -lcrypto', '') - - libnames = options.shared_openssl_libname.split(',') - o['libraries'] += ['-l%s' % s for s in libnames] - - if options.shared_openssl_libpath: - o['libraries'] += ['-L%s' % options.shared_openssl_libpath] - - if options.shared_openssl_includes: - o['include_dirs'] += [options.shared_openssl_includes] - else: - o['cflags'] += cflags.split() + configure_library('openssl', o) def configure_fullystatic(o): @@ -812,7 +812,7 @@ def configure_intl(o): with_intl = options.with_intl with_icu_source = options.with_icu_source have_icu_path = bool(options.with_icu_path) - if have_icu_path and with_intl: + if have_icu_path and with_intl != 'none': print 'Error: Cannot specify both --with-icu-path and --with-intl' sys.exit(1) elif have_icu_path: @@ -840,21 +840,19 @@ def configure_intl(o): # ICU from pkg-config. o['variables']['v8_enable_i18n_support'] = 1 pkgicu = pkg_config('icu-i18n') - if not pkgicu: + if pkgicu[0] is None: print 'Error: could not load pkg-config data for "icu-i18n".' print 'See above errors or the README.md.' sys.exit(1) - (libs, cflags) = pkgicu + (libs, cflags, libpath) = pkgicu + # libpath provides linker path which may contain spaces + o['libraries'] += [libpath] + # safe to split, cannot contain spaces o['libraries'] += libs.split() o['cflags'] += cflags.split() # use the "system" .gyp o['variables']['icu_gyp_path'] = 'tools/icu/icu-system.gyp' return - else: - print 'Error: unknown value --with-intl=%s' % with_intl - sys.exit(1) - # Note: non-ICU implementations could use other 'with_intl' - # values. # this is just the 'deps' dir. Used for unpacking. icu_parent_path = os.path.join(root_dir, 'deps') @@ -1008,9 +1006,9 @@ if (options.dest_os): flavor = GetFlavor(flavor_params) configure_node(output) -configure_libz(output) -configure_http_parser(output) -configure_libuv(output) +configure_library('zlib', output) +configure_library('http_parser', output) +configure_library('libuv', output) configure_v8(output) configure_openssl(output) configure_winsdk(output) diff --git a/deps/cares/cares.gyp b/deps/cares/cares.gyp index dfa35a25ef5e56..8fd8662e1bdf6f 100644 --- a/deps/cares/cares.gyp +++ b/deps/cares/cares.gyp @@ -26,7 +26,6 @@ 'direct_dependent_settings': { 'include_dirs': [ 'include' ] }, - 'defines': [ 'HAVE_CONFIG_H' ], 'sources': [ 'common.gypi', 'include/ares.h', @@ -96,7 +95,6 @@ 'src/inet_ntop.c', 'src/ares_inet_net_pton.h', 'src/setup_once.h', - 'src/windows_port.c' ], 'conditions': [ [ 'library=="static_library"', { @@ -107,7 +105,7 @@ [ 'OS=="win"', { 'include_dirs': [ 'config/win32' ], 'sources': [ - 'config/win32/ares_config.h', + 'src/config-win32.h', 'src/windows_port.c', 'src/ares_getenv.c', 'src/ares_iphlpapi.h', @@ -126,6 +124,7 @@ '-Wextra', '-Wno-unused-parameter' ], + 'defines': [ 'HAVE_CONFIG_H' ], }], [ 'OS not in "win android"', { 'cflags': [ diff --git a/deps/cares/config/win32/ares_config.h b/deps/cares/config/win32/ares_config.h deleted file mode 100644 index 6ded638093f8f7..00000000000000 --- a/deps/cares/config/win32/ares_config.h +++ /dev/null @@ -1,369 +0,0 @@ -#ifndef __ARES_CONFIG_WIN32_H -#define __ARES_CONFIG_WIN32_H - -/* when building c-ares library */ -#define CARES_BUILDING_LIBRARY 1 - -/* Copyright (C) 2004 - 2008 by Daniel Stenberg et al - * - * Permission to use, copy, modify, and distribute this software and its - * documentation for any purpose and without fee is hereby granted, provided - * that the above copyright notice appear in all copies and that both that - * copyright notice and this permission notice appear in supporting - * documentation, and that the name of M.I.T. not be used in advertising or - * publicity pertaining to distribution of the software without specific, - * written prior permission. M.I.T. makes no representations about the - * suitability of this software for any purpose. It is provided "as is" - * without express or implied warranty. - */ - -#define ARES_ - -/* ================================================================ */ -/* ares/config-win32.h - Hand crafted config file for Windows */ -/* ================================================================ */ - -/* ---------------------------------------------------------------- */ -/* HEADER FILES */ -/* ---------------------------------------------------------------- */ - -/* Define if you have the header file. */ -#if defined(__MINGW32__) || defined(__POCC__) -#define HAVE_GETOPT_H 1 -#endif - -/* Define if you have the header file. */ -#define HAVE_LIMITS_H 1 - -/* Define if you have the header file. */ -#ifndef __SALFORDC__ -#define HAVE_PROCESS_H 1 -#endif - -/* Define if you have the header file. */ -#define HAVE_SIGNAL_H 1 - -/* Define if you have the header file */ -#if defined(__MINGW32__) -#define HAVE_SYS_TIME_H 1 -#endif - -/* Define if you have the header file. */ -#define HAVE_TIME_H 1 - -/* Define if you have the header file. */ -#if defined(__MINGW32__) || defined(__WATCOMC__) || defined(__LCC__) || \ - defined(__POCC__) -#define HAVE_UNISTD_H 1 -#endif - -/* Define if you have the windows.h header file. */ -#define HAVE_WINDOWS_H 1 - -/* Define if you have the header file. */ -#define HAVE_WINSOCK_H 1 - -/* Define if you have the header file. */ -#ifndef __SALFORDC__ -#define HAVE_WINSOCK2_H 1 -#endif - -/* Define if you have the header file. */ -#ifndef __SALFORDC__ -#define HAVE_WS2TCPIP_H 1 -#endif - -/* ---------------------------------------------------------------- */ -/* OTHER HEADER INFO */ -/* ---------------------------------------------------------------- */ - -/* Define if sig_atomic_t is an available typedef. */ -#define HAVE_SIG_ATOMIC_T 1 - -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define if you can safely include both and . */ -/* #define TIME_WITH_SYS_TIME 1 */ - -/* ---------------------------------------------------------------- */ -/* FUNCTIONS */ -/* ---------------------------------------------------------------- */ - -/* Define if you have the closesocket function. */ -#define HAVE_CLOSESOCKET 1 - -/* Define if you have the gethostname function. */ -#define HAVE_GETHOSTNAME 1 - -/* Define if you have the ioctlsocket function. */ -#define HAVE_IOCTLSOCKET 1 - -/* Define if you have a working ioctlsocket FIONBIO function. */ -#define HAVE_IOCTLSOCKET_FIONBIO 1 - -/* Define if you have the strcasecmp function. */ -/* #define HAVE_STRCASECMP 1 */ - -/* Define if you have the getenv function. */ -#define HAVE_GETENV 1 - -/* Define if you have the strdup function. */ -#define HAVE_STRDUP 1 - -/* Define if you have the stricmp function. */ -#define HAVE_STRICMP 1 - -/* Define if you have the strncasecmp function. */ -/* #define HAVE_STRNCASECMP 1 */ - -/* Define if you have the strnicmp function. */ -#define HAVE_STRNICMP 1 - -/* Define if you have the recv function. */ -#define HAVE_RECV 1 - -/* Define to the type of arg 1 for recv. */ -#define RECV_TYPE_ARG1 SOCKET - -/* Define to the type of arg 2 for recv. */ -#define RECV_TYPE_ARG2 char * - -/* Define to the type of arg 3 for recv. */ -#define RECV_TYPE_ARG3 int - -/* Define to the type of arg 4 for recv. */ -#define RECV_TYPE_ARG4 int - -/* Define to the function return type for recv. */ -#define RECV_TYPE_RETV int - -/* Define if you have the recvfrom function. */ -#define HAVE_RECVFROM 1 - -/* Define to the type of arg 1 for recvfrom. */ -#define RECVFROM_TYPE_ARG1 SOCKET - -/* Define to the type pointed by arg 2 for recvfrom. */ -#define RECVFROM_TYPE_ARG2 char - -/* Define to the type of arg 3 for recvfrom. */ -#define RECVFROM_TYPE_ARG3 int - -/* Define to the type of arg 4 for recvfrom. */ -#define RECVFROM_TYPE_ARG4 int - -/* Define to the type pointed by arg 5 for recvfrom. */ -#define RECVFROM_TYPE_ARG5 struct sockaddr - -/* Define to the type pointed by arg 6 for recvfrom. */ -#define RECVFROM_TYPE_ARG6 int - -/* Define to the function return type for recvfrom. */ -#define RECVFROM_TYPE_RETV int - -/* Define if you have the send function. */ -#define HAVE_SEND 1 - -/* Define to the type of arg 1 for send. */ -#define SEND_TYPE_ARG1 SOCKET - -/* Define to the type qualifier of arg 2 for send. */ -#define SEND_QUAL_ARG2 const - -/* Define to the type of arg 2 for send. */ -#define SEND_TYPE_ARG2 char * - -/* Define to the type of arg 3 for send. */ -#define SEND_TYPE_ARG3 int - -/* Define to the type of arg 4 for send. */ -#define SEND_TYPE_ARG4 int - -/* Define to the function return type for send. */ -#define SEND_TYPE_RETV int - -/* Specifics for the Watt-32 tcp/ip stack */ -#ifdef WATT32 - #define SOCKET int - #define NS_INADDRSZ 4 - #define HAVE_ARPA_NAMESER_H 1 - #define HAVE_ARPA_INET_H 1 - #define HAVE_NETDB_H 1 - #define HAVE_NETINET_IN_H 1 - #define HAVE_SYS_SOCKET_H 1 - #define HAVE_NETINET_TCP_H 1 - #define HAVE_AF_INET6 1 - #define HAVE_PF_INET6 1 - #define HAVE_STRUCT_IN6_ADDR 1 - #define HAVE_STRUCT_SOCKADDR_IN6 1 - #undef HAVE_WINSOCK_H - #undef HAVE_WINSOCK2_H - #undef HAVE_WS2TCPIP_H -#endif - -/* ---------------------------------------------------------------- */ -/* TYPEDEF REPLACEMENTS */ -/* ---------------------------------------------------------------- */ - -/* Define this if in_addr_t is not an available 'typedefed' type */ -#define in_addr_t unsigned long - -/* Define as the return type of signal handlers (int or void). */ -#define RETSIGTYPE void - -/* Define ssize_t if it is not an available 'typedefed' type */ -#ifndef _SSIZE_T_DEFINED -# if (defined(__WATCOMC__) && (__WATCOMC__ >= 1240)) || \ - defined(__POCC__) || \ - defined(__MINGW32__) -# elif defined(_WIN64) -# define _SSIZE_T_DEFINED -# define ssize_t __int64 -# else -# define _SSIZE_T_DEFINED -# define ssize_t int -# endif -#endif - -/* ---------------------------------------------------------------- */ -/* TYPE SIZES */ -/* ---------------------------------------------------------------- */ - -/* The size of `int', as computed by sizeof. */ -#define SIZEOF_INT 4 - -/* The size of `short', as computed by sizeof. */ -#define SIZEOF_SHORT 2 - -/* The size of `size_t', as computed by sizeof. */ -#if defined(_WIN64) -# define SIZEOF_SIZE_T 8 -#else -# define SIZEOF_SIZE_T 4 -#endif - -/* ---------------------------------------------------------------- */ -/* STRUCT RELATED */ -/* ---------------------------------------------------------------- */ - -/* Define this if you have struct addrinfo */ -#define HAVE_STRUCT_ADDRINFO 1 - -/* Define this if you have struct sockaddr_storage */ -#ifndef __SALFORDC__ -#define HAVE_STRUCT_SOCKADDR_STORAGE 1 -#endif - -/* Define this if you have struct timeval */ -#define HAVE_STRUCT_TIMEVAL 1 - -/* ---------------------------------------------------------------- */ -/* COMPILER SPECIFIC */ -/* ---------------------------------------------------------------- */ - -/* Define to avoid VS2005 complaining about portable C functions */ -#if defined(_MSC_VER) && (_MSC_VER >= 1400) -#define _CRT_SECURE_NO_DEPRECATE 1 -#define _CRT_NONSTDC_NO_DEPRECATE 1 -#endif - -/* Officially, Microsoft's Windows SDK versions 6.X do not support Windows - 2000 as a supported build target. VS2008 default installations provide an - embedded Windows SDK v6.0A along with the claim that Windows 2000 is a - valid build target for VS2008. Popular belief is that binaries built using - Windows SDK versions 6.X and Windows 2000 as a build target are functional */ -#if defined(_MSC_VER) && (_MSC_VER >= 1500) -# define VS2008_MINIMUM_TARGET 0x0500 -#endif - -/* When no build target is specified VS2008 default build target is Windows - Vista, which leaves out even Winsows XP. If no build target has been given - for VS2008 we will target the minimum Officially supported build target, - which happens to be Windows XP. */ -#if defined(_MSC_VER) && (_MSC_VER >= 1500) -# define VS2008_DEFAULT_TARGET 0x0501 -#endif - -/* VS2008 default target settings and minimum build target check */ -#if defined(_MSC_VER) && (_MSC_VER >= 1500) -# ifndef _WIN32_WINNT -# define _WIN32_WINNT VS2008_DEFAULT_TARGET -# endif -# ifndef WINVER -# define WINVER VS2008_DEFAULT_TARGET -# endif -# if (_WIN32_WINNT < VS2008_MINIMUM_TARGET) || (WINVER < VS2008_MINIMUM_TARGET) -# error VS2008 does not support Windows build targets prior to Windows 2000 -# endif -#endif - -/* When no build target is specified Pelles C 5.00 and later default build - target is Windows Vista. We override default target to be Windows 2000. */ -#if defined(__POCC__) && (__POCC__ >= 500) -# ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x0500 -# endif -# ifndef WINVER -# define WINVER 0x0500 -# endif -#endif - -/* Availability of freeaddrinfo, getaddrinfo and getnameinfo functions is - quite convoluted, compiler dependent and even build target dependent. */ -#if defined(HAVE_WS2TCPIP_H) -# if defined(__POCC__) -# define HAVE_FREEADDRINFO 1 -# define HAVE_GETADDRINFO 1 -# define HAVE_GETNAMEINFO 1 -# elif defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0501) -# define HAVE_FREEADDRINFO 1 -# define HAVE_GETADDRINFO 1 -# define HAVE_GETNAMEINFO 1 -# elif defined(_MSC_VER) && (_MSC_VER >= 1200) -# define HAVE_FREEADDRINFO 1 -# define HAVE_GETADDRINFO 1 -# define HAVE_GETNAMEINFO 1 -# endif -#endif - -#if defined(__POCC__) -# ifndef _MSC_VER -# error Microsoft extensions /Ze compiler option is required -# endif -# ifndef __POCC__OLDNAMES -# error Compatibility names /Go compiler option is required -# endif -#endif - -/* ---------------------------------------------------------------- */ -/* IPV6 COMPATIBILITY */ -/* ---------------------------------------------------------------- */ - -/* Define this if you have address family AF_INET6 */ -#ifdef HAVE_WINSOCK2_H -#define HAVE_AF_INET6 1 -#endif - -/* Define this if you have protocol family PF_INET6 */ -#ifdef HAVE_WINSOCK2_H -#define HAVE_PF_INET6 1 -#endif - -/* Define this if you have struct in6_addr */ -#ifdef HAVE_WS2TCPIP_H -#define HAVE_STRUCT_IN6_ADDR 1 -#endif - -/* Define this if you have struct sockaddr_in6 */ -#ifdef HAVE_WS2TCPIP_H -#define HAVE_STRUCT_SOCKADDR_IN6 1 -#endif - -/* Define this if you have sockaddr_in6 with scopeid */ -#ifdef HAVE_WS2TCPIP_H -#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 -#endif - - -#endif /* __ARES_CONFIG_WIN32_H */ diff --git a/deps/cares/include/ares.h b/deps/cares/include/ares.h index 3091064b5113b4..f9abe854d5846a 100644 --- a/deps/cares/include/ares.h +++ b/deps/cares/include/ares.h @@ -29,55 +29,8 @@ # define WIN32 #endif -/*************************** libuv patch ***************/ - -/* - * We want to avoid autoconf altogether since there are a finite number of - * operating systems and simply build c-ares. Therefore we do not want the - * configurations provided by ares_build.h since we are always statically - * linking c-ares into libuv. Having a system dependent ares_build.h forces - * all users of ares.h to include the correct ares_build.h. We do not care - * about the linking checks provided by ares_rules.h. This would complicate - * the libuv build process. - */ - - -#if defined(WIN32) -/* Configure process defines this to 1 when it finds out that system */ -/* header file ws2tcpip.h must be included by the external interface. */ -/* #undef CARES_PULL_WS2TCPIP_H */ -# include -# include -# include - -#else /* Not Windows */ - -# include -# include -# include -#endif - -#if 0 -/* The size of `long', as computed by sizeof. */ -#define CARES_SIZEOF_LONG 4 -#endif - -/* Integral data type used for ares_socklen_t. */ -#define CARES_TYPEOF_ARES_SOCKLEN_T socklen_t - -#if 0 -/* The size of `ares_socklen_t', as computed by sizeof. */ -#define CARES_SIZEOF_ARES_SOCKLEN_T 4 -#endif - /* Data type definition of ares_socklen_t. */ -typedef int ares_socklen_t; - -#if 0 /* libuv disabled */ -#include "ares_rules.h" /* c-ares rules enforcement */ -#endif - -/*********************** end libuv patch ***************/ +typedef unsigned ares_socklen_t; #include diff --git a/deps/cares/include/ares_version.h b/deps/cares/include/ares_version.h index cdd49924cc4b80..2c9146d7d954a6 100644 --- a/deps/cares/include/ares_version.h +++ b/deps/cares/include/ares_version.h @@ -7,11 +7,11 @@ #define ARES_VERSION_MAJOR 1 #define ARES_VERSION_MINOR 10 -#define ARES_VERSION_PATCH 0 +#define ARES_VERSION_PATCH 1 #define ARES_VERSION ((ARES_VERSION_MAJOR<<16)|\ (ARES_VERSION_MINOR<<8)|\ (ARES_VERSION_PATCH)) -#define ARES_VERSION_STR "1.10.0-DEV" +#define ARES_VERSION_STR "1.10.1-DEV" #if (ARES_VERSION >= 0x010700) # define CARES_HAVE_ARES_LIBRARY_INIT 1 diff --git a/deps/cares/src/ares__read_line.c b/deps/cares/src/ares__read_line.c index bd9504fc4f0be0..6ebd42fe6efb34 100644 --- a/deps/cares/src/ares__read_line.c +++ b/deps/cares/src/ares__read_line.c @@ -61,7 +61,10 @@ int ares__read_line(FILE *fp, char **buf, size_t *bufsize) /* Allocate more space. */ newbuf = realloc(*buf, *bufsize * 2); if (!newbuf) - return ARES_ENOMEM; + { + free(*buf); + return ARES_ENOMEM; + } *buf = newbuf; *bufsize *= 2; } diff --git a/deps/cares/src/ares_gethostbyname.c b/deps/cares/src/ares_gethostbyname.c index 2b27b2e1048fcc..ba6b0f0f0c5661 100644 --- a/deps/cares/src/ares_gethostbyname.c +++ b/deps/cares/src/ares_gethostbyname.c @@ -188,8 +188,9 @@ static void host_callback(void *arg, int status, int timeouts, else if (hquery->sent_family == AF_INET6) { status = ares_parse_aaaa_reply(abuf, alen, &host, NULL, NULL); - if ((status == ARES_ENODATA || status == ARES_EBADRESP) && - hquery->want_family == AF_UNSPEC) { + if ((status == ARES_ENODATA || status == ARES_EBADRESP || + (status == ARES_SUCCESS && host && host->h_addr_list[0] == NULL)) && + hquery->want_family == AF_UNSPEC) { /* The query returned something but either there were no AAAA records (e.g. just CNAME) or the response was malformed. Try looking up A instead. */ diff --git a/deps/cares/src/ares_getnameinfo.c b/deps/cares/src/ares_getnameinfo.c index 5b9f6386b29e01..b0bc6da868cdda 100644 --- a/deps/cares/src/ares_getnameinfo.c +++ b/deps/cares/src/ares_getnameinfo.c @@ -281,6 +281,8 @@ static char *lookup_service(unsigned short port, int flags, struct servent se; #endif char tmpbuf[4096]; + char *name; + size_t name_len; if (port) { @@ -323,14 +325,20 @@ static char *lookup_service(unsigned short port, int flags, #endif } if (sep && sep->s_name) - /* get service name */ - strcpy(tmpbuf, sep->s_name); + { + /* get service name */ + name = sep->s_name; + } else - /* get port as a string */ - sprintf(tmpbuf, "%u", (unsigned int)ntohs(port)); - if (strlen(tmpbuf) < buflen) + { + /* get port as a string */ + sprintf(tmpbuf, "%u", (unsigned int)ntohs(port)); + name = tmpbuf; + } + name_len = strlen(name); + if (name_len < buflen) /* return it if buffer big enough */ - strcpy(buf, tmpbuf); + memcpy(buf, name, name_len + 1); else /* avoid reusing previous one */ buf[0] = '\0'; diff --git a/deps/cares/src/ares_getsock.c b/deps/cares/src/ares_getsock.c index 07d2854cfd1538..22d344679faa60 100644 --- a/deps/cares/src/ares_getsock.c +++ b/deps/cares/src/ares_getsock.c @@ -30,9 +30,7 @@ int ares_getsock(ares_channel channel, /* Are there any active queries? */ int active_queries = !ares__is_list_empty(&(channel->all_queries)); - for (i = 0; - (i < channel->nservers) && (sockindex < ARES_GETSOCK_MAXNUM); - i++) + for (i = 0; i < channel->nservers; i++) { server = &channel->servers[i]; /* We only need to register interest in UDP sockets if we have @@ -40,7 +38,7 @@ int ares_getsock(ares_channel channel, */ if (active_queries && server->udp_socket != ARES_SOCKET_BAD) { - if(sockindex >= numsocks) + if(sockindex >= numsocks || sockindex >= ARES_GETSOCK_MAXNUM) break; socks[sockindex] = server->udp_socket; bitmap |= ARES_GETSOCK_READABLE(setbits, sockindex); @@ -52,7 +50,7 @@ int ares_getsock(ares_channel channel, */ if (server->tcp_socket != ARES_SOCKET_BAD) { - if(sockindex >= numsocks) + if(sockindex >= numsocks || sockindex >= ARES_GETSOCK_MAXNUM) break; socks[sockindex] = server->tcp_socket; bitmap |= ARES_GETSOCK_READABLE(setbits, sockindex); diff --git a/deps/cares/src/ares_init.c b/deps/cares/src/ares_init.c index 05bf70c3b6d80f..bd3336e5d63e46 100644 --- a/deps/cares/src/ares_init.c +++ b/deps/cares/src/ares_init.c @@ -266,7 +266,10 @@ int ares_dup(ares_channel *dest, ares_channel src) which is most of them */ rc = ares_save_options(src, &opts, &optmask); if(rc) + { + ares_destroy_options(&opts); return rc; + } /* Then create the new channel with those options */ rc = ares_init_options(dest, &opts, optmask); @@ -1158,20 +1161,24 @@ static int init_by_resolv_conf(ares_channel channel) FILE *fp; size_t linesize; int error; + int update_domains; /* Don't read resolv.conf and friends if we don't have to */ if (ARES_CONFIG_CHECK(channel)) return ARES_SUCCESS; + /* Only update search domains if they're not already specified */ + update_domains = (channel->ndomains == -1); + fp = fopen(PATH_RESOLV_CONF, "r"); if (fp) { while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS) { - if ((p = try_config(line, "domain", ';'))) + if ((p = try_config(line, "domain", ';')) && update_domains) status = config_domain(channel, p); else if ((p = try_config(line, "lookup", ';')) && !channel->lookups) status = config_lookup(channel, p, "bind", "file"); - else if ((p = try_config(line, "search", ';'))) + else if ((p = try_config(line, "search", ';')) && update_domains) status = set_search(channel, p); else if ((p = try_config(line, "nameserver", ';')) && channel->nservers == -1) @@ -1410,7 +1417,7 @@ static int init_by_defaults(ares_channel channel) goto error; } - } WHILE_FALSE; + } while (res != 0); dot = strchr(hostname, '.'); if (dot) { diff --git a/deps/cares/src/ares_ipv6.h b/deps/cares/src/ares_ipv6.h index 6f1022a76f5338..1830076a81092a 100644 --- a/deps/cares/src/ares_ipv6.h +++ b/deps/cares/src/ares_ipv6.h @@ -71,7 +71,7 @@ struct addrinfo #endif #endif -/* Defined in ares_net_pton.c for no particular reason. */ +/* Defined in inet_net_pton.c for no particular reason. */ extern const struct ares_in6_addr ares_in6addr_any; /* :: */ diff --git a/deps/cares/src/ares_nowarn.c b/deps/cares/src/ares_nowarn.c index 397e70b01844a1..d4bd272c6d9e8c 100644 --- a/deps/cares/src/ares_nowarn.c +++ b/deps/cares/src/ares_nowarn.c @@ -1,5 +1,5 @@ -/* Copyright (C) 2010-2012 by Daniel Stenberg +/* Copyright (C) 2010-2013 by Daniel Stenberg * * Permission to use, copy, modify, and distribute this * software and its documentation for any purpose and without @@ -21,6 +21,10 @@ # include #endif +#ifdef HAVE_LIMITS_H +#include +#endif + #if defined(__INTEL_COMPILER) && defined(__unix__) #ifdef HAVE_NETINET_IN_H @@ -36,13 +40,43 @@ #include "ares_nowarn.h" -#define CARES_MASK_USHORT (~(unsigned short) 0) -#define CARES_MASK_UINT (~(unsigned int) 0) -#define CARES_MASK_ULONG (~(unsigned long) 0) +#if (SIZEOF_SHORT == 2) +# define CARES_MASK_SSHORT 0x7FFF +# define CARES_MASK_USHORT 0xFFFF +#elif (SIZEOF_SHORT == 4) +# define CARES_MASK_SSHORT 0x7FFFFFFF +# define CARES_MASK_USHORT 0xFFFFFFFF +#elif (SIZEOF_SHORT == 8) +# define CARES_MASK_SSHORT 0x7FFFFFFFFFFFFFFF +# define CARES_MASK_USHORT 0xFFFFFFFFFFFFFFFF +#else +# error "SIZEOF_SHORT not defined" +#endif -#define CARES_MASK_SSHORT (CARES_MASK_USHORT >> 1) -#define CARES_MASK_SINT (CARES_MASK_UINT >> 1) -#define CARES_MASK_SLONG (CARES_MASK_ULONG >> 1) +#if (SIZEOF_INT == 2) +# define CARES_MASK_SINT 0x7FFF +# define CARES_MASK_UINT 0xFFFF +#elif (SIZEOF_INT == 4) +# define CARES_MASK_SINT 0x7FFFFFFF +# define CARES_MASK_UINT 0xFFFFFFFF +#elif (SIZEOF_INT == 8) +# define CARES_MASK_SINT 0x7FFFFFFFFFFFFFFF +# define CARES_MASK_UINT 0xFFFFFFFFFFFFFFFF +#elif (SIZEOF_INT == 16) +# define CARES_MASK_SINT 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF +# define CARES_MASK_UINT 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF +#else +# error "SIZEOF_INT not defined" +#endif + +#ifndef HAVE_LIMITS_H +/* systems without we guess have 32 bit longs */ +#define CARES_MASK_SLONG 0x7FFFFFFFL +#define CARES_MASK_ULONG 0xFFFFFFFFUL +#else +#define CARES_MASK_ULONG ULONG_MAX +#define CARES_MASK_SLONG LONG_MAX +#endif /* ** unsigned size_t to signed long diff --git a/deps/cares/src/ares_options.c b/deps/cares/src/ares_options.c index 76d82dfb94d0a8..cf88433a1b5ae4 100644 --- a/deps/cares/src/ares_options.c +++ b/deps/cares/src/ares_options.c @@ -158,6 +158,9 @@ int ares_set_servers_csv(ares_channel channel, return ARES_SUCCESS; /* blank all servers */ csv = malloc(i + 2); + if (!csv) + return ARES_ENOMEM; + strcpy(csv, _csv); if (csv[i-1] != ',') { /* make parsing easier by ensuring ending ',' */ csv[i] = ','; diff --git a/deps/cares/src/ares_parse_soa_reply.c b/deps/cares/src/ares_parse_soa_reply.c index da1c6dccaf13ee..9a578a1f19a226 100644 --- a/deps/cares/src/ares_parse_soa_reply.c +++ b/deps/cares/src/ares_parse_soa_reply.c @@ -86,7 +86,10 @@ ares_parse_soa_reply(const unsigned char *abuf, int alen, /* allocate result struct */ soa = ares_malloc_data(ARES_DATATYPE_SOA_REPLY); if (!soa) - return ARES_ENOMEM; + { + status = ARES_ENOMEM; + goto failed_stat; + } /* nsname */ status = ares__expand_name_for_response(aptr, abuf, alen, &soa->nsname, &len); diff --git a/deps/cares/src/ares_private.h b/deps/cares/src/ares_private.h index ab5be5a58aa6c9..8f486a449a8ae2 100644 --- a/deps/cares/src/ares_private.h +++ b/deps/cares/src/ares_private.h @@ -310,12 +310,7 @@ struct ares_channeldata { /* return true if now is exactly check time or later */ int ares__timedout(struct timeval *now, struct timeval *check); -/* add the specific number of milliseconds to the time in the first argument */ -int ares__timeadd(struct timeval *now, - int millisecs); -/* return time offset between now and (future) check, in milliseconds */ -long ares__timeoffset(struct timeval *now, - struct timeval *check); + /* returns ARES_SUCCESS if library has been initialized */ int ares_library_initialized(void); void ares__send_query(ares_channel channel, struct query *query, diff --git a/deps/cares/src/ares_process.c b/deps/cares/src/ares_process.c index bbeca5e737e73f..020a1319e55ea4 100644 --- a/deps/cares/src/ares_process.c +++ b/deps/cares/src/ares_process.c @@ -102,8 +102,7 @@ int ares__timedout(struct timeval *now, } /* add the specific number of milliseconds to the time in the first argument */ -int ares__timeadd(struct timeval *now, - int millisecs) +static void timeadd(struct timeval *now, int millisecs) { now->tv_sec += millisecs/1000; now->tv_usec += (millisecs%1000)*1000; @@ -112,19 +111,8 @@ int ares__timeadd(struct timeval *now, ++(now->tv_sec); now->tv_usec -= 1000000; } - - return 0; -} - -/* return time offset between now and (future) check, in milliseconds */ -long ares__timeoffset(struct timeval *now, - struct timeval *check) -{ - return (check->tv_sec - now->tv_sec)*1000 + - (check->tv_usec - now->tv_usec)/1000; } - /* * generic process function */ @@ -831,8 +819,7 @@ void ares__send_query(ares_channel channel, struct query *query, timeplus = channel->timeout << (query->try_count / channel->nservers); timeplus = (timeplus * (9 + (rand () & 7))) / 16; query->timeout = *now; - ares__timeadd(&query->timeout, - timeplus); + timeadd(&query->timeout, timeplus); /* Keep track of queries bucketed by timeout, so we can process * timeout events quickly. */ diff --git a/deps/cares/src/ares_rules.h b/deps/cares/src/ares_rules.h index f94c5b59165e7a..44f08f807c3cb7 100644 --- a/deps/cares/src/ares_rules.h +++ b/deps/cares/src/ares_rules.h @@ -68,11 +68,6 @@ * Verify that some macros are actually defined. */ -#ifndef CARES_SIZEOF_LONG -# error "CARES_SIZEOF_LONG definition is missing!" - Error Compilation_aborted_CARES_SIZEOF_LONG_is_missing -#endif - #ifndef CARES_TYPEOF_ARES_SOCKLEN_T # error "CARES_TYPEOF_ARES_SOCKLEN_T definition is missing!" Error Compilation_aborted_CARES_TYPEOF_ARES_SOCKLEN_T_is_missing @@ -91,15 +86,6 @@ #define CareschkszGE(t1, t2) sizeof(t1) >= sizeof(t2) ? 1 : -1 -/* - * Verify that the size previously defined and expected for long - * is the same as the one reported by sizeof() at compile time. - */ - -typedef char - __cares_rule_01__ - [CareschkszEQ(long, CARES_SIZEOF_LONG)]; - /* * Verify that the size previously defined and expected for * ares_socklen_t is actually the the same as the one reported diff --git a/deps/cares/src/ares_search.c b/deps/cares/src/ares_search.c index ec076405adb7a1..f9558a9a50f463 100644 --- a/deps/cares/src/ares_search.c +++ b/deps/cares/src/ares_search.c @@ -239,7 +239,7 @@ static int single_domain(ares_channel channel, const char *name, char **s) /* If the name contains a trailing dot, then the single query is the name * sans the trailing dot. */ - if (name[len - 1] == '.') + if ((len > 0) && (name[len - 1] == '.')) { *s = strdup(name); return (*s) ? ARES_SUCCESS : ARES_ENOMEM; diff --git a/deps/cares/src/ares_setup.h b/deps/cares/src/ares_setup.h index 18e14557cde56d..dee3e6ba6e4c05 100644 --- a/deps/cares/src/ares_setup.h +++ b/deps/cares/src/ares_setup.h @@ -75,9 +75,9 @@ /* please, do it beyond the point further indicated in this file. */ /* ================================================================ */ -#if 1 /* libuv hack */ -#include /* needed on windows */ -#else +#if 1 +# define SIZEOF_SHORT 2 +#else /* Disabled for the gyp-ified build. */ /* * c-ares external interface definitions are also used internally, * and might also include required system header files to define them. @@ -90,7 +90,7 @@ */ #include -#endif /* libuv hack */ +#endif /* ================================================================= */ /* No system header file shall be included in this file before this */ diff --git a/deps/cares/src/ares_timeout.c b/deps/cares/src/ares_timeout.c index 0b5a435f510f4c..293e4af02161e8 100644 --- a/deps/cares/src/ares_timeout.c +++ b/deps/cares/src/ares_timeout.c @@ -23,6 +23,13 @@ #include "ares.h" #include "ares_private.h" +/* return time offset between now and (future) check, in milliseconds */ +static long timeoffset(struct timeval *now, struct timeval *check) +{ + return (check->tv_sec - now->tv_sec)*1000 + + (check->tv_usec - now->tv_usec)/1000; +} + /* WARNING: Beware that this is linear in the number of outstanding * requests! You are probably far better off just calling ares_process() * once per second, rather than calling ares_timeout() to figure out @@ -53,7 +60,7 @@ struct timeval *ares_timeout(ares_channel channel, struct timeval *maxtv, query = list_node->data; if (query->timeout.tv_sec == 0) continue; - offset = ares__timeoffset(&now, &query->timeout); + offset = timeoffset(&now, &query->timeout); if (offset < 0) offset = 0; if (min_offset == -1 || offset < min_offset) diff --git a/deps/cares/src/config-win32.h b/deps/cares/src/config-win32.h new file mode 100644 index 00000000000000..1245ba2abbef89 --- /dev/null +++ b/deps/cares/src/config-win32.h @@ -0,0 +1,385 @@ +#ifndef HEADER_CARES_CONFIG_WIN32_H +#define HEADER_CARES_CONFIG_WIN32_H + +/* Copyright (C) 2004 - 2011 by Daniel Stenberg et al + * + * Permission to use, copy, modify, and distribute this software and its + * documentation for any purpose and without fee is hereby granted, provided + * that the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of M.I.T. not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. M.I.T. makes no representations about the + * suitability of this software for any purpose. It is provided "as is" + * without express or implied warranty. + */ + +/* ================================================================ */ +/* c-ares/config-win32.h - Hand crafted config file for Windows */ +/* ================================================================ */ + +/* ---------------------------------------------------------------- */ +/* HEADER FILES */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the header file. */ +#define HAVE_ASSERT_H 1 + +/* Define if you have the header file. */ +#define HAVE_ERRNO_H 1 + +/* Define if you have the header file. */ +#if defined(__MINGW32__) || defined(__POCC__) +#define HAVE_GETOPT_H 1 +#endif + +/* Define if you have the header file. */ +#define HAVE_LIMITS_H 1 + +/* Define if you have the header file. */ +#ifndef __SALFORDC__ +#define HAVE_PROCESS_H 1 +#endif + +/* Define if you have the header file. */ +#define HAVE_SIGNAL_H 1 + +/* Define if you have the header file */ +/* #define HAVE_SYS_TIME_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_TIME_H 1 + +/* Define if you have the header file. */ +#if defined(__MINGW32__) || defined(__WATCOMC__) || defined(__LCC__) || \ + defined(__POCC__) +#define HAVE_UNISTD_H 1 +#endif + +/* Define if you have the header file. */ +#define HAVE_WINDOWS_H 1 + +/* Define if you have the header file. */ +#define HAVE_WINSOCK_H 1 + +/* Define if you have the header file. */ +#ifndef __SALFORDC__ +#define HAVE_WINSOCK2_H 1 +#endif + +/* Define if you have the header file. */ +#ifndef __SALFORDC__ +#define HAVE_WS2TCPIP_H 1 +#endif + +/* ---------------------------------------------------------------- */ +/* OTHER HEADER INFO */ +/* ---------------------------------------------------------------- */ + +/* Define if sig_atomic_t is an available typedef. */ +#define HAVE_SIG_ATOMIC_T 1 + +/* Define if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define if you can safely include both and . */ +/* #define TIME_WITH_SYS_TIME 1 */ + +/* ---------------------------------------------------------------- */ +/* FUNCTIONS */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the closesocket function. */ +#define HAVE_CLOSESOCKET 1 + +/* Define if you have the getenv function. */ +#define HAVE_GETENV 1 + +/* Define if you have the gethostname function. */ +#define HAVE_GETHOSTNAME 1 + +/* Define if you have the ioctlsocket function. */ +#define HAVE_IOCTLSOCKET 1 + +/* Define if you have a working ioctlsocket FIONBIO function. */ +#define HAVE_IOCTLSOCKET_FIONBIO 1 + +/* Define if you have the strcasecmp function. */ +/* #define HAVE_STRCASECMP 1 */ + +/* Define if you have the strdup function. */ +#define HAVE_STRDUP 1 + +/* Define if you have the stricmp function. */ +#define HAVE_STRICMP 1 + +/* Define if you have the strncasecmp function. */ +/* #define HAVE_STRNCASECMP 1 */ + +/* Define if you have the strnicmp function. */ +#define HAVE_STRNICMP 1 + +/* Define if you have the recv function. */ +#define HAVE_RECV 1 + +/* Define to the type of arg 1 for recv. */ +#define RECV_TYPE_ARG1 SOCKET + +/* Define to the type of arg 2 for recv. */ +#define RECV_TYPE_ARG2 char * + +/* Define to the type of arg 3 for recv. */ +#define RECV_TYPE_ARG3 int + +/* Define to the type of arg 4 for recv. */ +#define RECV_TYPE_ARG4 int + +/* Define to the function return type for recv. */ +#define RECV_TYPE_RETV int + +/* Define if you have the recvfrom function. */ +#define HAVE_RECVFROM 1 + +/* Define to the type of arg 1 for recvfrom. */ +#define RECVFROM_TYPE_ARG1 SOCKET + +/* Define to the type pointed by arg 2 for recvfrom. */ +#define RECVFROM_TYPE_ARG2 char + +/* Define to the type of arg 3 for recvfrom. */ +#define RECVFROM_TYPE_ARG3 int + +/* Define to the type of arg 4 for recvfrom. */ +#define RECVFROM_TYPE_ARG4 int + +/* Define to the type pointed by arg 5 for recvfrom. */ +#define RECVFROM_TYPE_ARG5 struct sockaddr + +/* Define to the type pointed by arg 6 for recvfrom. */ +#define RECVFROM_TYPE_ARG6 int + +/* Define to the function return type for recvfrom. */ +#define RECVFROM_TYPE_RETV int + +/* Define if you have the send function. */ +#define HAVE_SEND 1 + +/* Define to the type of arg 1 for send. */ +#define SEND_TYPE_ARG1 SOCKET + +/* Define to the type qualifier of arg 2 for send. */ +#define SEND_QUAL_ARG2 const + +/* Define to the type of arg 2 for send. */ +#define SEND_TYPE_ARG2 char * + +/* Define to the type of arg 3 for send. */ +#define SEND_TYPE_ARG3 int + +/* Define to the type of arg 4 for send. */ +#define SEND_TYPE_ARG4 int + +/* Define to the function return type for send. */ +#define SEND_TYPE_RETV int + +/* Specifics for the Watt-32 tcp/ip stack. */ +#ifdef WATT32 + #define SOCKET int + #define NS_INADDRSZ 4 + #define HAVE_ARPA_NAMESER_H 1 + #define HAVE_ARPA_INET_H 1 + #define HAVE_NETDB_H 1 + #define HAVE_NETINET_IN_H 1 + #define HAVE_SYS_SOCKET_H 1 + #define HAVE_NETINET_TCP_H 1 + #define HAVE_AF_INET6 1 + #define HAVE_PF_INET6 1 + #define HAVE_STRUCT_IN6_ADDR 1 + #define HAVE_STRUCT_SOCKADDR_IN6 1 + #undef HAVE_WINSOCK_H + #undef HAVE_WINSOCK2_H + #undef HAVE_WS2TCPIP_H +#endif + +/* ---------------------------------------------------------------- */ +/* TYPEDEF REPLACEMENTS */ +/* ---------------------------------------------------------------- */ + +/* Define if in_addr_t is not an available 'typedefed' type. */ +#define in_addr_t unsigned long + +/* Define to the return type of signal handlers (int or void). */ +#define RETSIGTYPE void + +/* Define if ssize_t is not an available 'typedefed' type. */ +#ifndef _SSIZE_T_DEFINED +# if (defined(__WATCOMC__) && (__WATCOMC__ >= 1240)) || \ + defined(__POCC__) || \ + defined(__MINGW32__) +# elif defined(_WIN64) +# define _SSIZE_T_DEFINED +# define ssize_t __int64 +# else +# define _SSIZE_T_DEFINED +# define ssize_t int +# endif +#endif + +/* ---------------------------------------------------------------- */ +/* TYPE SIZES */ +/* ---------------------------------------------------------------- */ + +/* Define to the size of `int', as computed by sizeof. */ +#define SIZEOF_INT 4 + +/* Define to the size of `short', as computed by sizeof. */ +#define SIZEOF_SHORT 2 + +/* Define to the size of `size_t', as computed by sizeof. */ +#if defined(_WIN64) +# define SIZEOF_SIZE_T 8 +#else +# define SIZEOF_SIZE_T 4 +#endif + +/* ---------------------------------------------------------------- */ +/* STRUCT RELATED */ +/* ---------------------------------------------------------------- */ + +/* Define if you have struct addrinfo. */ +#define HAVE_STRUCT_ADDRINFO 1 + +/* Define if you have struct sockaddr_storage. */ +#if !defined(__SALFORDC__) && !defined(__BORLANDC__) +#define HAVE_STRUCT_SOCKADDR_STORAGE 1 +#endif + +/* Define if you have struct timeval. */ +#define HAVE_STRUCT_TIMEVAL 1 + +/* ---------------------------------------------------------------- */ +/* COMPILER SPECIFIC */ +/* ---------------------------------------------------------------- */ + +/* Define to avoid VS2005 complaining about portable C functions. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +# define _CRT_SECURE_NO_DEPRECATE 1 +# define _CRT_NONSTDC_NO_DEPRECATE 1 +#endif + +/* Officially, Microsoft's Windows SDK versions 6.X do not support Windows + 2000 as a supported build target. VS2008 default installations provide + an embedded Windows SDK v6.0A along with the claim that Windows 2000 is + a valid build target for VS2008. Popular belief is that binaries built + with VS2008 using Windows SDK versions 6.X and Windows 2000 as a build + target are functional. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1500) +# define VS2008_MIN_TARGET 0x0500 +#endif + +/* When no build target is specified VS2008 default build target is Windows + Vista, which leaves out even Winsows XP. If no build target has been given + for VS2008 we will target the minimum Officially supported build target, + which happens to be Windows XP. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1500) +# define VS2008_DEF_TARGET 0x0501 +#endif + +/* VS2008 default target settings and minimum build target check. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1500) +# ifndef _WIN32_WINNT +# define _WIN32_WINNT VS2008_DEF_TARGET +# endif +# ifndef WINVER +# define WINVER VS2008_DEF_TARGET +# endif +# if (_WIN32_WINNT < VS2008_MIN_TARGET) || (WINVER < VS2008_MIN_TARGET) +# error VS2008 does not support Windows build targets prior to Windows 2000 +# endif +#endif + +/* When no build target is specified Pelles C 5.00 and later default build + target is Windows Vista. We override default target to be Windows 2000. */ +#if defined(__POCC__) && (__POCC__ >= 500) +# ifndef _WIN32_WINNT +# define _WIN32_WINNT 0x0500 +# endif +# ifndef WINVER +# define WINVER 0x0500 +# endif +#endif + +/* Availability of freeaddrinfo, getaddrinfo and getnameinfo functions is + quite convoluted, compiler dependent and even build target dependent. */ +#if defined(HAVE_WS2TCPIP_H) +# if defined(__POCC__) +# define HAVE_FREEADDRINFO 1 +# define HAVE_GETADDRINFO 1 +# define HAVE_GETNAMEINFO 1 +# elif defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0501) +# define HAVE_FREEADDRINFO 1 +# define HAVE_GETADDRINFO 1 +# define HAVE_GETNAMEINFO 1 +# elif defined(_MSC_VER) && (_MSC_VER >= 1200) +# define HAVE_FREEADDRINFO 1 +# define HAVE_GETADDRINFO 1 +# define HAVE_GETNAMEINFO 1 +# endif +#endif + +#if defined(__POCC__) +# ifndef _MSC_VER +# error Microsoft extensions /Ze compiler option is required +# endif +# ifndef __POCC__OLDNAMES +# error Compatibility names /Go compiler option is required +# endif +#endif + +/* ---------------------------------------------------------------- */ +/* IPV6 COMPATIBILITY */ +/* ---------------------------------------------------------------- */ + +/* Define if you have address family AF_INET6. */ +#ifdef HAVE_WINSOCK2_H +#define HAVE_AF_INET6 1 +#endif + +/* Define if you have protocol family PF_INET6. */ +#ifdef HAVE_WINSOCK2_H +#define HAVE_PF_INET6 1 +#endif + +/* Define if you have struct in6_addr. */ +#ifdef HAVE_WS2TCPIP_H +#define HAVE_STRUCT_IN6_ADDR 1 +#endif + +/* Define if you have struct sockaddr_in6. */ +#ifdef HAVE_WS2TCPIP_H +#define HAVE_STRUCT_SOCKADDR_IN6 1 +#endif + +/* Define if you have sockaddr_in6 with scopeid. */ +#ifdef HAVE_WS2TCPIP_H +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 +#endif + +/* ---------------------------------------------------------------- */ +/* Win CE */ +/* ---------------------------------------------------------------- */ + +/* FIXME: A proper config-win32ce.h should be created to hold these */ + +/* + * System error codes for Windows CE + */ + +#if defined(_WIN32_WCE) && !defined(HAVE_ERRNO_H) +# define ENOENT ERROR_FILE_NOT_FOUND +# define ESRCH ERROR_PATH_NOT_FOUND +# define ENOMEM ERROR_NOT_ENOUGH_MEMORY +# define ENOSPC ERROR_INVALID_PARAMETER +#endif + +#endif /* HEADER_CARES_CONFIG_WIN32_H */ diff --git a/deps/uv/AUTHORS b/deps/uv/AUTHORS index 6929fff222cd91..a0e3dd46f092f4 100644 --- a/deps/uv/AUTHORS +++ b/deps/uv/AUTHORS @@ -181,3 +181,19 @@ Johan Bergström Alex Mo Luis Martinez de Bartolome Michael Penick +Michael +Massimiliano Torromeo +TomCrypto +Brett Vickers +Ole André Vadla Ravnås +Kazuho Oku +Ryan Phillips +Brian Green +Devchandra Meetei Leishangthem +Corey Farrell +Per Nilsson +Alan Rogers +Daryl Haresign +Rui Abreu Ferreira +João Reis +farblue68 diff --git a/deps/uv/ChangeLog b/deps/uv/ChangeLog index 7bbe5027a7aa28..e5c79808d2e1cc 100644 --- a/deps/uv/ChangeLog +++ b/deps/uv/ChangeLog @@ -1,4 +1,108 @@ -2015.02.27, Version 1.4.2 (Stable) +2015.05.07, Version 1.5.0 (Stable), 4e77f74c7b95b639b3397095db1bc5bcc016c203 + +Changes since version 1.4.2: + +* doc: clarify that the thread pool primites are not thread safe (Andrius + Bentkus) + +* aix: always deregister closing fds from epoll (Michael) + +* unix: fix glibc-2.20+ macro incompatibility (Massimiliano Torromeo) + +* doc: add Sphinx plugin for generating links to man pages (Saúl Ibarra + Corretgé) + +* doc: link system and library calls to man pages (Saúl Ibarra Corretgé) + +* doc: document uv_getnameinfo_t.{host|service} (Saúl Ibarra Corretgé) + +* build: update the location of gyp (Stephen von Takach) + +* win: name all anonymous structs and unions (TomCrypto) + +* linux: work around epoll bug in kernels 3.10-3.19 (Ben Noordhuis) + +* darwin: fix size calculation in select() fallback (Ole André Vadla Ravnås) + +* solaris: fix setsockopt for multicast options (Julien Gilli) + +* test: fix race condition in multithreaded test (Ben Noordhuis) + +* doc: fix long lines in tty.rst (Ben Noordhuis) + +* test: use UV_TTY_MODE_* values in tty test (Ben Noordhuis) + +* unix: don't clobber errno in uv_tty_reset_mode() (Ben Noordhuis) + +* unix: reject non-tty fds in uv_tty_init() (Ben Noordhuis) + +* win: fix pipe blocking writes (Alexis Campailla) + +* build: fix cross-compiling for iOS (Steven Kabbes) + +* win: remove unnecessary malloc.h + +* include: use `extern "c++"` for defining C++ code (Kazuho Oku) + +* unix: reap child on execvp() failure (Ryan Phillips) + +* windows: fix handle leak on EMFILE (Brian Green) + +* test: fix tty_file, close handle if initialized (Saúl Ibarra Corretgé) + +* doc: clarify what uv_*_open accepts (Saúl Ibarra Corretgé) + +* doc: clarify that we don't maintain external doc resources (Saúl Ibarra + Corretgé) + +* build: add documentation for ninja support (Devchandra Meetei Leishangthem) + +* doc: document uv_buf_t members (Corey Farrell) + +* linux: fix epoll_pwait() fallback on arm64 (Ben Noordhuis) + +* android: fix compilation warning (Saúl Ibarra Corretgé) + +* unix: don't close the fds we just setup (Sam Roberts) + +* test: spawn child replacing std{out,err} to stderr (Saúl Ibarra Corretgé) + +* unix: fix swapping fds order in uv_spawn (Saúl Ibarra Corretgé) + +* unix: fix potential bug if dup2 fails in uv_spawn (Saúl Ibarra Corretgé) + +* test: remove LOG and LOGF variadic macros (Saúl Ibarra Corretgé) + +* win: fix uv_fs_access on directories (Saúl Ibarra Corretgé) + +* win: fix of double free in uv_uptime (Per Nilsson) + +* unix: open "/dev/null" instead of "/" for emfile_fd (Alan Rogers) + +* docs: add some missing words (Daryl Haresign) + +* unix: clean up uv_fs_open() O_CLOEXEC logic (Ben Noordhuis) + +* build: set SONAME for shared library in uv.gyp (Rui Abreu Ferreira) + +* windows: define snprintf replacement as inline instead of static (Rui Abreu + Ferreira) + +* win: fix unlink of readonly files (João Reis) + +* doc: fix uv_run(UV_RUN_DEFAULT) description (Ben Noordhuis) + +* linux: intercept syscall when running under memory sanitizer (Keno Fischer) + +* aix: fix uv_interface_addresses return value (farblue68) + +* windows: defer reporting TCP write failure until next tick (Saúl Ibarra + Corretgé) + +* test: add test for deferred TCP write failure (Saúl Ibarra Corretgé) + + +2015.02.27, Version 1.4.2 (Stable), 1a7391348a11d5450c0f69c828d5302e2cb842eb Changes since version 1.4.1: diff --git a/deps/uv/Makefile.am b/deps/uv/Makefile.am index 9c511db47a6c8f..b9fb80c6738b52 100644 --- a/deps/uv/Makefile.am +++ b/deps/uv/Makefile.am @@ -226,6 +226,7 @@ test_run_tests_SOURCES = test/blackhole-server.c \ test/test-tcp-write-to-half-open-connection.c \ test/test-tcp-write-after-connect.c \ test/test-tcp-writealot.c \ + test/test-tcp-write-fail.c \ test/test-tcp-try-write.c \ test/test-tcp-write-queue-order.c \ test/test-thread-equal.c \ diff --git a/deps/uv/README.md b/deps/uv/README.md index a267f0d5b527e5..a7da8b898c581d 100644 --- a/deps/uv/README.md +++ b/deps/uv/README.md @@ -72,19 +72,23 @@ NOTE: Windows users need to use make.bat instead of plain 'make'. Documentation can be browsed online [here](http://docs.libuv.org). +The [tests and benchmarks](https://github.com/libuv/libuv/tree/master/test) +also serve as API specification and usage examples. + ### Other resources * [An Introduction to libuv](http://nikhilm.github.com/uvbook/) — An overview of libuv with tutorials. * [LXJS 2012 talk](http://www.youtube.com/watch?v=nGn60vDSxQ4) — High-level introductory talk about libuv. - * [Tests and benchmarks](https://github.com/libuv/libuv/tree/master/test) - — API specification and usage examples. * [libuv-dox](https://github.com/thlorenz/libuv-dox) — Documenting types and methods of libuv, mostly by reading uv.h. * [learnuv](https://github.com/thlorenz/learnuv) — Learn uv for fun and profit, a self guided workshop to libuv. +These resources are not handled by libuv maintainers and might be out of +date. Please verify it before opening new issues. + ## Build Instructions For GCC there are two build methods: via autotools or via [GYP][]. @@ -113,8 +117,6 @@ To have GYP generate build script for another system, checkout GYP into the project tree manually: $ git clone https://chromium.googlesource.com/external/gyp.git build/gyp - OR - $ svn co http://gyp.googlecode.com/svn/trunk build/gyp ### Unix @@ -153,6 +155,15 @@ Run: Note for UNIX users: compile your project with `-D_LARGEFILE_SOURCE` and `-D_FILE_OFFSET_BITS=64`. GYP builds take care of that automatically. +### Using Ninja + +To use ninja for build on ninja supported platforms, run: + + $ ./gyp_uv.py -f ninja + $ ninja -C out/Debug #for debug build OR + $ ninja -C out/Release + + ### Running tests Run: diff --git a/deps/uv/configure.ac b/deps/uv/configure.ac index 9473d5ffcb09d2..71cb4704138c57 100644 --- a/deps/uv/configure.ac +++ b/deps/uv/configure.ac @@ -13,7 +13,7 @@ # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. AC_PREREQ(2.57) -AC_INIT([libuv], [1.4.2], [https://github.com/libuv/libuv/issues]) +AC_INIT([libuv], [1.5.0], [https://github.com/libuv/libuv/issues]) AC_CONFIG_MACRO_DIR([m4]) m4_include([m4/libuv-extra-automake-flags.m4]) m4_include([m4/as_case.m4]) diff --git a/deps/uv/docs/src/conf.py b/deps/uv/docs/src/conf.py index f614fc5b434b24..b9eaa137432dea 100644 --- a/deps/uv/docs/src/conf.py +++ b/deps/uv/docs/src/conf.py @@ -38,7 +38,7 @@ def get_libuv_version(): # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath('sphinx-plugins')) # -- General configuration ------------------------------------------------ @@ -48,7 +48,7 @@ def get_libuv_version(): # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = [] +extensions = ['manpage'] # Add any paths that contain templates here, relative to this directory. templates_path = ['templates'] diff --git a/deps/uv/docs/src/design.rst b/deps/uv/docs/src/design.rst index 63141bedf58438..34c3cff68e54ca 100644 --- a/deps/uv/docs/src/design.rst +++ b/deps/uv/docs/src/design.rst @@ -40,7 +40,7 @@ The I/O loop The I/O (or event) loop is the central part of libuv. It establishes the content for all I/O operations, and it's meant to be tied to a single thread. One can run multiple event loops as long as each runs in a different thread. The libuv event loop (or any other API involving -the loop or handles, for that matter) **is not thread-safe** except stated otherwise. +the loop or handles, for that matter) **is not thread-safe** except where stated otherwise. The event loop follows the rather usual single threaded asynchronous I/O approach: all (network) I/O is performed on non-blocking sockets which are polled using the best mechanism available @@ -113,7 +113,7 @@ stages of a loop iteration: .. note:: While the polling mechanism is different, libuv makes the execution model consistent - Unix systems and Windows. + across Unix systems and Windows. File I/O diff --git a/deps/uv/docs/src/dns.rst b/deps/uv/docs/src/dns.rst index 3b15377f91e419..1d881580966315 100644 --- a/deps/uv/docs/src/dns.rst +++ b/deps/uv/docs/src/dns.rst @@ -51,6 +51,18 @@ Public members Loop that started this getnameinfo request and where completion will be reported. Readonly. +.. c:member:: char[NI_MAXHOST] uv_getnameinfo_t.host + + Char array containing the resulting host. It's null terminated. + + .. versionchanged:: 1.3.0 the field is declared as public. + +.. c:member:: char[NI_MAXSERV] uv_getnameinfo_t.service + + Char array containing the resulting service. It's null terminated. + + .. versionchanged:: 1.3.0 the field is declared as public. + .. seealso:: The :c:type:`uv_req_t` members also apply. @@ -59,7 +71,7 @@ API .. c:function:: int uv_getaddrinfo(uv_loop_t* loop, uv_getaddrinfo_t* req, uv_getaddrinfo_cb getaddrinfo_cb, const char* node, const char* service, const struct addrinfo* hints) - Asynchronous ``getaddrinfo(3)``. + Asynchronous :man:`getaddrinfo(3)`. Either node or service may be NULL but not both. @@ -84,7 +96,7 @@ API .. c:function:: int uv_getnameinfo(uv_loop_t* loop, uv_getnameinfo_t* req, uv_getnameinfo_cb getnameinfo_cb, const struct sockaddr* addr, int flags) - Asynchronous ``getnameinfo(3)``. + Asynchronous :man:`getnameinfo(3)`. Returns 0 on success or an error code < 0 on failure. If successful, the callback will get called sometime in the future with the lookup result. diff --git a/deps/uv/docs/src/fs.rst b/deps/uv/docs/src/fs.rst index cd535f756fc1c9..c2a3fc252a1ffe 100644 --- a/deps/uv/docs/src/fs.rst +++ b/deps/uv/docs/src/fs.rst @@ -162,46 +162,46 @@ API .. c:function:: int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) - Equivalent to ``close(2)``. + Equivalent to :man:`close(2)`. .. c:function:: int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, int mode, uv_fs_cb cb) - Equivalent to ``open(2)``. + Equivalent to :man:`open(2)`. .. c:function:: int uv_fs_read(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb) - Equivalent to ``preadv(2)``. + Equivalent to :man:`preadv(2)`. .. c:function:: int uv_fs_unlink(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) - Equivalent to ``unlink(2)``. + Equivalent to :man:`unlink(2)`. .. c:function:: int uv_fs_write(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb) - Equivalent to ``pwritev(2)``. + Equivalent to :man:`pwritev(2)`. .. c:function:: int uv_fs_mkdir(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb) - Equivalent to ``mkdir(2)``. + Equivalent to :man:`mkdir(2)`. .. note:: `mode` is currently not implemented on Windows. .. c:function:: int uv_fs_mkdtemp(uv_loop_t* loop, uv_fs_t* req, const char* tpl, uv_fs_cb cb) - Equivalent to ``mkdtemp(3)``. + Equivalent to :man:`mkdtemp(3)`. .. note:: The result can be found as a null terminated string at `req->path`. .. c:function:: int uv_fs_rmdir(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) - Equivalent to ``rmdir(2)``. + Equivalent to :man:`rmdir(2)`. .. c:function:: int uv_fs_scandir(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, uv_fs_cb cb) .. c:function:: int uv_fs_scandir_next(uv_fs_t* req, uv_dirent_t* ent) - Equivalent to ``scandir(3)``, with a slightly different API. Once the callback + Equivalent to :man:`scandir(3)`, with a slightly different API. Once the callback for the request is called, the user can use :c:func:`uv_fs_scandir_next` to get `ent` populated with the next directory entry data. When there are no more entries ``UV_EOF`` will be returned. @@ -210,49 +210,49 @@ API .. c:function:: int uv_fs_fstat(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) .. c:function:: int uv_fs_lstat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) - Equivalent to ``(f/l)stat(2)``. + Equivalent to :man:`stat(2)`, :man:`fstat(2)` and :man:`fstat(2)` respectively. .. c:function:: int uv_fs_rename(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, uv_fs_cb cb) - Equivalent to ``rename(2)``. + Equivalent to :man:`rename(2)`. .. c:function:: int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) - Equivalent to ``fsync(2)``. + Equivalent to :man:`fsync(2)`. .. c:function:: int uv_fs_fdatasync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) - Equivalent to ``fdatasync(2)``. + Equivalent to :man:`fdatasync(2)`. .. c:function:: int uv_fs_ftruncate(uv_loop_t* loop, uv_fs_t* req, uv_file file, int64_t offset, uv_fs_cb cb) - Equivalent to ``ftruncate(2)``. + Equivalent to :man:`ftruncate(2)`. .. c:function:: int uv_fs_sendfile(uv_loop_t* loop, uv_fs_t* req, uv_file out_fd, uv_file in_fd, int64_t in_offset, size_t length, uv_fs_cb cb) - Limited equivalent to ``sendfile(2)``. + Limited equivalent to :man:`sendfile(2)`. .. c:function:: int uv_fs_access(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb) - Equivalent to ``access(2)`` on Unix. Windows uses ``GetFileAttributesW()``. + Equivalent to :man:`access(2)` on Unix. Windows uses ``GetFileAttributesW()``. .. c:function:: int uv_fs_chmod(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb) .. c:function:: int uv_fs_fchmod(uv_loop_t* loop, uv_fs_t* req, uv_file file, int mode, uv_fs_cb cb) - Equivalent to ``(f)chmod(2)``. + Equivalent to :man:`chmod(2)` and :man:`fchmod(2)` respectively. .. c:function:: int uv_fs_utime(uv_loop_t* loop, uv_fs_t* req, const char* path, double atime, double mtime, uv_fs_cb cb) .. c:function:: int uv_fs_futime(uv_loop_t* loop, uv_fs_t* req, uv_file file, double atime, double mtime, uv_fs_cb cb) - Equivalent to ``(f)utime(s)(2)``. + Equivalent to :man:`utime(2)` and :man:`futime(2)` respectively. .. c:function:: int uv_fs_link(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, uv_fs_cb cb) - Equivalent to ``link(2)``. + Equivalent to :man:`link(2)`. .. c:function:: int uv_fs_symlink(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, int flags, uv_fs_cb cb) - Equivalent to ``symlink(2)``. + Equivalent to :man:`symlink(2)`. .. note:: On Windows the `flags` parameter can be specified to control how the symlink will @@ -265,12 +265,12 @@ API .. c:function:: int uv_fs_readlink(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) - Equivalent to ``readlink(2)``. + Equivalent to :man:`readlink(2)`. .. c:function:: int uv_fs_chown(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb) .. c:function:: int uv_fs_fchown(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb) - Equivalent to ``(f)chown(2)``. + Equivalent to :man:`chown(2)` and :man:`fchown(2)` respectively. .. note:: These functions are not implemented on Windows. diff --git a/deps/uv/docs/src/loop.rst b/deps/uv/docs/src/loop.rst index 203672bd34f00a..2a01d796375e8e 100644 --- a/deps/uv/docs/src/loop.rst +++ b/deps/uv/docs/src/loop.rst @@ -92,7 +92,9 @@ API specified mode: - UV_RUN_DEFAULT: Runs the event loop until there are no more active and - referenced handles or requests. Always returns zero. + referenced handles or requests. Returns non-zero if :c:func:`uv_stop` + was called and there are still active handles or requests. Returns + zero in all other cases. - UV_RUN_ONCE: Poll for i/o once. Note that this function blocks if there are no pending callbacks. Returns zero when done (no active handles or requests left), or non-zero if more callbacks are expected (meaning diff --git a/deps/uv/docs/src/misc.rst b/deps/uv/docs/src/misc.rst index 10c349e9b736f3..bb97a260057fc8 100644 --- a/deps/uv/docs/src/misc.rst +++ b/deps/uv/docs/src/misc.rst @@ -15,6 +15,17 @@ Data types Buffer data type. + .. c:member:: char* uv_buf_t.base + + Pointer to the base of the buffer. Readonly. + + .. c:member:: size_t uv_buf_t.len + + Total bytes in the buffer. Readonly. + + .. note:: + On Windows this field is ULONG. + .. c:type:: uv_file Cross platform representation of a file handle. @@ -26,7 +37,7 @@ Data types .. c:type:: uv_os_fd_t Abstract representation of a file descriptor. On Unix systems this is a - `typedef` of `int` and on Windows fa `HANDLE`. + `typedef` of `int` and on Windows a `HANDLE`. .. c:type:: uv_rusage_t @@ -101,7 +112,8 @@ API descriptor. Usually this will be used during initialization to guess the type of the stdio streams. - For ``isatty()`` functionality use this function and test for ``UV_TTY``. + For :man:`isatty(3)` equivalent functionality use this function and test + for ``UV_TTY``. .. c:function:: unsigned int uv_version(void) @@ -195,8 +207,8 @@ API .. c:function:: int uv_inet_ntop(int af, const void* src, char* dst, size_t size) .. c:function:: int uv_inet_pton(int af, const char* src, void* dst) - Cross-platform IPv6-capable implementation of the 'standard' ``inet_ntop()`` - and ``inet_pton()`` functions. On success they return 0. In case of error + Cross-platform IPv6-capable implementation of :man:`inet_ntop(3)` + and :man:`inet_pton(3)`. On success they return 0. In case of error the target `dst` pointer is unmodified. .. c:function:: int uv_exepath(char* buffer, size_t* size) diff --git a/deps/uv/docs/src/pipe.rst b/deps/uv/docs/src/pipe.rst index 8f8402c29bbadd..df896a0583447f 100644 --- a/deps/uv/docs/src/pipe.rst +++ b/deps/uv/docs/src/pipe.rst @@ -40,6 +40,10 @@ API .. versionchanged:: 1.2.1 the file descriptor is set to non-blocking mode. + .. note:: + The passed file descriptor or HANDLE is not checked for its type, but + it's required that it represents a valid pipe. + .. c:function:: int uv_pipe_bind(uv_pipe_t* handle, const char* name) Bind the pipe to a file path (Unix) or a name (Windows). diff --git a/deps/uv/docs/src/poll.rst b/deps/uv/docs/src/poll.rst index 907cb1a613dfbb..6dc41839ac1e92 100644 --- a/deps/uv/docs/src/poll.rst +++ b/deps/uv/docs/src/poll.rst @@ -5,7 +5,7 @@ =================================== Poll handles are used to watch file descriptors for readability and -writability, similar to the purpose of poll(2). +writability, similar to the purpose of :man:`poll(2)`. The purpose of poll handles is to enable integrating external libraries that rely on the event loop to signal it about the socket status changes, like @@ -29,7 +29,7 @@ closed immediately after a call to :c:func:`uv_poll_stop` or :c:func:`uv_close`. .. note:: On windows only sockets can be polled with poll handles. On Unix any file - descriptor that would be accepted by poll(2) can be used. + descriptor that would be accepted by :man:`poll(2)` can be used. Data types diff --git a/deps/uv/docs/src/sphinx-plugins/manpage.py b/deps/uv/docs/src/sphinx-plugins/manpage.py new file mode 100644 index 00000000000000..1d1dc379f410ee --- /dev/null +++ b/deps/uv/docs/src/sphinx-plugins/manpage.py @@ -0,0 +1,46 @@ +# encoding: utf-8 + +# +# Copyright (c) 2013 Dariusz Dwornikowski. All rights reserved. +# +# Adapted from https://github.com/tdi/sphinxcontrib-manpage +# License: Apache 2 +# + + +import re + +from docutils import nodes, utils +from docutils.parsers.rst.roles import set_classes +from string import Template + + +def make_link_node(rawtext, app, name, manpage_num, options): + ref = app.config.man_url_regex + if not ref: + ref = "http://linux.die.net/man/%s/%s" % (manpage_num, name) + else: + s = Template(ref) + ref = s.substitute(num=manpage_num, topic=name) + set_classes(options) + node = nodes.reference(rawtext, "%s(%s)" % (name, manpage_num), refuri=ref, **options) + return node + + +def man_role(name, rawtext, text, lineno, inliner, options={}, content=[]): + app = inliner.document.settings.env.app + p = re.compile("([a-zA-Z0-9_\.-_]+)\((\d)\)") + m = p.match(text) + + manpage_num = m.group(2) + name = m.group(1) + node = make_link_node(rawtext, app, name, manpage_num, options) + return [node], [] + + +def setup(app): + app.info('Initializing manpage plugin') + app.add_role('man', man_role) + app.add_config_value('man_url_regex', None, 'env') + return + diff --git a/deps/uv/docs/src/stream.rst b/deps/uv/docs/src/stream.rst index 1f6682adc1cfc2..880f0e2ebc75d3 100644 --- a/deps/uv/docs/src/stream.rst +++ b/deps/uv/docs/src/stream.rst @@ -104,7 +104,7 @@ API .. c:function:: int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb) Start listening for incoming connections. `backlog` indicates the number of - connections the kernel might queue, same as ``listen(2)``. When a new + connections the kernel might queue, same as :man:`listen(2)`. When a new incoming connection is received the :c:type:`uv_connection_cb` callback is called. diff --git a/deps/uv/docs/src/tcp.rst b/deps/uv/docs/src/tcp.rst index 8baedde86c5c15..2b5d268ddd86e6 100644 --- a/deps/uv/docs/src/tcp.rst +++ b/deps/uv/docs/src/tcp.rst @@ -38,6 +38,10 @@ API .. versionchanged:: 1.2.1 the file descriptor is set to non-blocking mode. + .. note:: + The passed file descriptor or SOCKET is not checked for its type, but + it's required that it represents a valid stream socket. + .. c:function:: int uv_tcp_nodelay(uv_tcp_t* handle, int enable) Enable / disable Nagle's algorithm. diff --git a/deps/uv/docs/src/threadpool.rst b/deps/uv/docs/src/threadpool.rst index 89f00844ef2c65..18949507e75004 100644 --- a/deps/uv/docs/src/threadpool.rst +++ b/deps/uv/docs/src/threadpool.rst @@ -18,6 +18,10 @@ libuv preallocates and initializes the maximum number of threads allowed by ``UV_THREADPOOL_SIZE``. This causes a relatively minor memory overhead (~1MB for 128 threads) but increases the performance of threading at runtime. +.. note:: + Note that even though a global thread pool which is shared across all events + loops is used, the functions are not thread safe. + Data types ---------- diff --git a/deps/uv/docs/src/tty.rst b/deps/uv/docs/src/tty.rst index 6c20c84bf75e58..18f34ef46d97b5 100644 --- a/deps/uv/docs/src/tty.rst +++ b/deps/uv/docs/src/tty.rst @@ -24,14 +24,14 @@ Data types :: - typedef enum { - /* Initial/normal terminal mode */ - UV_TTY_MODE_NORMAL, - /* Raw input mode (On Windows, ENABLE_WINDOW_INPUT is also enabled) */ - UV_TTY_MODE_RAW, - /* Binary-safe I/O mode for IPC (Unix-only) */ - UV_TTY_MODE_IO - } uv_tty_mode_t; + typedef enum { + /* Initial/normal terminal mode */ + UV_TTY_MODE_NORMAL, + /* Raw input mode (On Windows, ENABLE_WINDOW_INPUT is also enabled) */ + UV_TTY_MODE_RAW, + /* Binary-safe I/O mode for IPC (Unix-only) */ + UV_TTY_MODE_IO + } uv_tty_mode_t; @@ -58,18 +58,22 @@ API `readable`, specifies if you plan on calling :c:func:`uv_read_start` with this stream. stdin is readable, stdout is not. - On Unix this function will try to open ``/dev/tty`` and use it if the passed file - descriptor refers to a TTY. This lets libuv put the tty in non-blocking mode - without affecting other processes that share the tty. + On Unix this function will try to open ``/dev/tty`` and use it if the passed + file descriptor refers to a TTY. This lets libuv put the tty in non-blocking + mode without affecting other processes that share the tty. .. note:: - If opening ``/dev/tty`` fails, libuv falls back to blocking writes for non-readable - TTY streams. + If opening ``/dev/tty`` fails, libuv falls back to blocking writes for + non-readable TTY streams. + + .. versionchanged:: 1.5.0: trying to initialize a TTY stream with a file + descriptor that refers to a file returns `UV_EINVAL` + on UNIX. .. c:function:: int uv_tty_set_mode(uv_tty_t*, uv_tty_mode_t mode) - .. versionchanged:: 1.2.0: the mode is specified as a :c:type:`uv_tty_mode_t` - value. + .. versionchanged:: 1.2.0: the mode is specified as a + :c:type:`uv_tty_mode_t` value. Set the TTY using the specified terminal mode. diff --git a/deps/uv/docs/src/udp.rst b/deps/uv/docs/src/udp.rst index 9c4aa2102bdcfc..ec7ce56d38f52c 100644 --- a/deps/uv/docs/src/udp.rst +++ b/deps/uv/docs/src/udp.rst @@ -122,6 +122,10 @@ API .. versionchanged:: 1.2.1 the file descriptor is set to non-blocking mode. + .. note:: + The passed file descriptor or SOCKET is not checked for its type, but + it's required that it represents a valid datagram socket. + .. c:function:: int uv_udp_bind(uv_udp_t* handle, const struct sockaddr* addr, unsigned int flags) Bind the UDP handle to an IP address and port. diff --git a/deps/uv/include/uv-version.h b/deps/uv/include/uv-version.h index 836d399d774a32..0b4e6d781c35f6 100644 --- a/deps/uv/include/uv-version.h +++ b/deps/uv/include/uv-version.h @@ -31,8 +31,8 @@ */ #define UV_VERSION_MAJOR 1 -#define UV_VERSION_MINOR 4 -#define UV_VERSION_PATCH 2 +#define UV_VERSION_MINOR 5 +#define UV_VERSION_PATCH 0 #define UV_VERSION_IS_RELEASE 1 #define UV_VERSION_SUFFIX "" diff --git a/deps/uv/include/uv-win.h b/deps/uv/include/uv-win.h index 24b22b31a9562b..fd844202b99a1a 100644 --- a/deps/uv/include/uv-win.h +++ b/deps/uv/include/uv-win.h @@ -43,16 +43,6 @@ typedef struct pollfd { # define LOCALE_INVARIANT 0x007f #endif -#ifndef _malloca -# if defined(_DEBUG) -# define _malloca(size) malloc(size) -# define _freea(ptr) free(ptr) -# else -# define _malloca(size) alloca(size) -# define _freea(ptr) -# endif -#endif - #include #include #include @@ -366,8 +356,8 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); struct { \ OVERLAPPED overlapped; \ size_t queued_bytes; \ - }; \ - }; \ + } io; \ + } u; \ struct uv_req_s* next_req; #define UV_WRITE_PRIVATE_FIELDS \ @@ -419,9 +409,9 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); int activecnt; \ uv_read_t read_req; \ union { \ - struct { uv_stream_connection_fields }; \ - struct { uv_stream_server_fields }; \ - }; + struct { uv_stream_connection_fields } conn; \ + struct { uv_stream_server_fields } serv; \ + } stream; #define uv_tcp_server_fields \ uv_tcp_accept_t* accept_reqs; \ @@ -437,9 +427,9 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); SOCKET socket; \ int delayed_error; \ union { \ - struct { uv_tcp_server_fields }; \ - struct { uv_tcp_connection_fields }; \ - }; + struct { uv_tcp_server_fields } serv; \ + struct { uv_tcp_connection_fields } conn; \ + } tcp; #define UV_UDP_PRIVATE_FIELDS \ SOCKET socket; \ @@ -476,9 +466,9 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); HANDLE handle; \ WCHAR* name; \ union { \ - struct { uv_pipe_server_fields }; \ - struct { uv_pipe_connection_fields }; \ - }; + struct { uv_pipe_server_fields } serv; \ + struct { uv_pipe_connection_fields } conn; \ + } pipe; /* TODO: put the parser states in an union - TTY handles are always */ /* half-duplex so read-state can safely overlap write-state. */ @@ -496,7 +486,7 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); unsigned char last_key_len; \ WCHAR last_utf16_high_surrogate; \ INPUT_RECORD last_input_record; \ - }; \ + } rd; \ struct { \ /* Used for writable TTY handles */ \ /* utf8-to-utf16 conversion state */ \ @@ -510,8 +500,8 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); unsigned short ansi_csi_argv[4]; \ COORD saved_position; \ WORD saved_attributes; \ - }; \ - }; + } wr; \ + } tty; #define UV_POLL_PRIVATE_FIELDS \ SOCKET socket; \ @@ -600,7 +590,7 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); /* TODO: remove me in 0.9. */ \ WCHAR* pathw; \ int fd; \ - }; \ + } file; \ union { \ struct { \ int mode; \ @@ -611,12 +601,12 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); uv_buf_t* bufs; \ int64_t offset; \ uv_buf_t bufsml[4]; \ - }; \ + } info; \ struct { \ double atime; \ double mtime; \ - }; \ - }; + } time; \ + } fs; #define UV_WORK_PRIVATE_FIELDS \ struct uv__work work_req; diff --git a/deps/uv/include/uv.h b/deps/uv/include/uv.h index 55f75218b58682..75b3a4a5d2f8bf 100644 --- a/deps/uv/include/uv.h +++ b/deps/uv/include/uv.h @@ -644,13 +644,13 @@ UV_EXTERN int uv_tty_reset_mode(void); UV_EXTERN int uv_tty_get_winsize(uv_tty_t*, int* width, int* height); #ifdef __cplusplus -} /* extern "C" */ +extern "C++" { inline int uv_tty_set_mode(uv_tty_t* handle, int mode) { return uv_tty_set_mode(handle, static_cast(mode)); } -extern "C" { +} #endif UV_EXTERN uv_handle_type uv_guess_handle(uv_file file); @@ -799,6 +799,7 @@ struct uv_getnameinfo_s { UV_REQ_FIELDS /* read-only */ uv_loop_t* loop; + /* host and service are marked as private, but they really aren't. */ UV_GETNAMEINFO_PRIVATE_FIELDS }; diff --git a/deps/uv/src/unix/aix.c b/deps/uv/src/unix/aix.c index ec800c7a323f4b..e21a9cc78b6979 100644 --- a/deps/uv/src/unix/aix.c +++ b/deps/uv/src/unix/aix.c @@ -1111,19 +1111,19 @@ int uv_interface_addresses(uv_interface_address_t** addresses, *count = 0; if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP))) { - return -ENOSYS; + return -errno; } if (ioctl(sockfd, SIOCGSIZIFCONF, &size) == -1) { - uv__close(sockfd); - return -ENOSYS; + SAVE_ERRNO(uv__close(sockfd)); + return -errno; } ifc.ifc_req = (struct ifreq*)malloc(size); ifc.ifc_len = size; if (ioctl(sockfd, SIOCGIFCONF, &ifc) == -1) { - uv__close(sockfd); - return -ENOSYS; + SAVE_ERRNO(uv__close(sockfd)); + return -errno; } #define ADDR_SIZE(p) MAX((p).sa_len, sizeof(p)) @@ -1141,8 +1141,8 @@ int uv_interface_addresses(uv_interface_address_t** addresses, memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name)); if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) { - uv__close(sockfd); - return -ENOSYS; + SAVE_ERRNO(uv__close(sockfd)); + return -errno; } if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING)) @@ -1218,16 +1218,23 @@ void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) { struct pollfd* events; uintptr_t i; uintptr_t nfds; + struct poll_ctl pc; assert(loop->watchers != NULL); events = (struct pollfd*) loop->watchers[loop->nwatchers]; nfds = (uintptr_t) loop->watchers[loop->nwatchers + 1]; - if (events == NULL) - return; - /* Invalidate events with same file descriptor */ - for (i = 0; i < nfds; i++) - if ((int) events[i].fd == fd) - events[i].fd = -1; + if (events != NULL) + /* Invalidate events with same file descriptor */ + for (i = 0; i < nfds; i++) + if ((int) events[i].fd == fd) + events[i].fd = -1; + + /* Remove the file descriptor from the poll set */ + pc.events = 0; + pc.cmd = PS_DELETE; + pc.fd = fd; + if(loop->backend_fd >= 0) + pollset_ctl(loop->backend_fd, &pc, 1); } diff --git a/deps/uv/src/unix/android-ifaddrs.c b/deps/uv/src/unix/android-ifaddrs.c index 3cda578dd1a94c..a99b0191d54808 100644 --- a/deps/uv/src/unix/android-ifaddrs.c +++ b/deps/uv/src/unix/android-ifaddrs.c @@ -24,6 +24,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "android-ifaddrs.h" +#include "uv-common.h" #include #include diff --git a/deps/uv/src/unix/fs.c b/deps/uv/src/unix/fs.c index e7eee2f9abc4ed..7792801e9b6fd6 100644 --- a/deps/uv/src/unix/fs.c +++ b/deps/uv/src/unix/fs.c @@ -202,6 +202,44 @@ static ssize_t uv__fs_mkdtemp(uv_fs_t* req) { } +static ssize_t uv__fs_open(uv_fs_t* req) { + static int no_cloexec_support; + int r; + + /* Try O_CLOEXEC before entering locks */ + if (no_cloexec_support == 0) { +#ifdef O_CLOEXEC + r = open(req->path, req->flags | O_CLOEXEC, req->mode); + if (r >= 0) + return r; + if (errno != EINVAL) + return r; + no_cloexec_support = 1; +#endif /* O_CLOEXEC */ + } + + if (req->cb != NULL) + uv_rwlock_rdlock(&req->loop->cloexec_lock); + + r = open(req->path, req->flags, req->mode); + + /* In case of failure `uv__cloexec` will leave error in `errno`, + * so it is enough to just set `r` to `-1`. + */ + if (r >= 0 && uv__cloexec(r, 1) != 0) { + r = uv__close(r); + if (r != 0 && r != -EINPROGRESS) + abort(); + r = -1; + } + + if (req->cb != NULL) + uv_rwlock_rdunlock(&req->loop->cloexec_lock); + + return r; +} + + static ssize_t uv__fs_read(uv_fs_t* req) { #if defined(__linux__) static int no_preadv; @@ -661,8 +699,22 @@ static void uv__to_stat(struct stat* src, uv_stat_t* dst) { dst->st_birthtim.tv_nsec = src->st_birthtimespec.tv_nsec; dst->st_flags = src->st_flags; dst->st_gen = src->st_gen; -#elif !defined(_AIX) && \ - (defined(_BSD_SOURCE) || defined(_SVID_SOURCE) || defined(_XOPEN_SOURCE)) +#elif defined(__ANDROID__) + dst->st_atim.tv_sec = src->st_atime; + dst->st_atim.tv_nsec = src->st_atime_nsec; + dst->st_mtim.tv_sec = src->st_mtime; + dst->st_mtim.tv_nsec = src->st_mtime_nsec; + dst->st_ctim.tv_sec = src->st_ctime; + dst->st_ctim.tv_nsec = src->st_ctime_nsec; + dst->st_birthtim.tv_sec = src->st_ctime; + dst->st_birthtim.tv_nsec = src->st_ctime_nsec; + dst->st_flags = 0; + dst->st_gen = 0; +#elif !defined(_AIX) && ( \ + defined(_BSD_SOURCE) || \ + defined(_SVID_SOURCE) || \ + defined(_XOPEN_SOURCE) || \ + defined(_DEFAULT_SOURCE)) dst->st_atim.tv_sec = src->st_atim.tv_sec; dst->st_atim.tv_nsec = src->st_atim.tv_nsec; dst->st_mtim.tv_sec = src->st_mtim.tv_sec; @@ -729,9 +781,6 @@ static void uv__fs_work(struct uv__work* w) { int retry_on_eintr; uv_fs_t* req; ssize_t r; -#ifdef O_CLOEXEC - static int no_cloexec_support; -#endif /* O_CLOEXEC */ req = container_of(w, uv_fs_t, work_req); retry_on_eintr = !(req->fs_type == UV_FS_CLOSE); @@ -760,6 +809,7 @@ static void uv__fs_work(struct uv__work* w) { X(LINK, link(req->path, req->new_path)); X(MKDIR, mkdir(req->path, req->mode)); X(MKDTEMP, uv__fs_mkdtemp(req)); + X(OPEN, uv__fs_open(req)); X(READ, uv__fs_read(req)); X(SCANDIR, uv__fs_scandir(req)); X(READLINK, uv__fs_readlink(req)); @@ -771,41 +821,10 @@ static void uv__fs_work(struct uv__work* w) { X(UNLINK, unlink(req->path)); X(UTIME, uv__fs_utime(req)); X(WRITE, uv__fs_write(req)); - case UV_FS_OPEN: -#ifdef O_CLOEXEC - /* Try O_CLOEXEC before entering locks */ - if (!no_cloexec_support) { - r = open(req->path, req->flags | O_CLOEXEC, req->mode); - if (r >= 0) - break; - if (errno != EINVAL) - break; - no_cloexec_support = 1; - } -#endif /* O_CLOEXEC */ - if (req->cb != NULL) - uv_rwlock_rdlock(&req->loop->cloexec_lock); - r = open(req->path, req->flags, req->mode); - - /* - * In case of failure `uv__cloexec` will leave error in `errno`, - * so it is enough to just set `r` to `-1`. - */ - if (r >= 0 && uv__cloexec(r, 1) != 0) { - r = uv__close(r); - if (r != 0 && r != -EINPROGRESS) - abort(); - r = -1; - } - if (req->cb != NULL) - uv_rwlock_rdunlock(&req->loop->cloexec_lock); - break; default: abort(); } - #undef X - } - while (r == -1 && errno == EINTR && retry_on_eintr); + } while (r == -1 && errno == EINTR && retry_on_eintr); if (r == -1) req->result = -errno; diff --git a/deps/uv/src/unix/internal.h b/deps/uv/src/unix/internal.h index 101dc745499f8d..31db5e29ea68b8 100644 --- a/deps/uv/src/unix/internal.h +++ b/deps/uv/src/unix/internal.h @@ -55,6 +55,9 @@ #define ACCESS_ONCE(type, var) \ (*(volatile type*) &(var)) +#define ROUND_UP(a, b) \ + ((a) % (b) ? ((a) + (b)) - ((a) % (b)) : (a)) + #define UNREACHABLE() \ do { \ assert(0 && "unreachable code"); \ diff --git a/deps/uv/src/unix/linux-core.c b/deps/uv/src/unix/linux-core.c index 33a735dc674f14..d07494dd654bb3 100644 --- a/deps/uv/src/unix/linux-core.c +++ b/deps/uv/src/unix/linux-core.c @@ -130,8 +130,13 @@ void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) { * * We pass in a dummy epoll_event, to work around a bug in old kernels. */ - if (loop->backend_fd >= 0) + if (loop->backend_fd >= 0) { + /* Work around a bug in kernels 3.10 to 3.19 where passing a struct that + * has the EPOLLWAKEUP flag set generates spurious audit syslog warnings. + */ + memset(&dummy, 0, sizeof(dummy)); uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_DEL, fd, &dummy); + } } diff --git a/deps/uv/src/unix/linux-syscalls.c b/deps/uv/src/unix/linux-syscalls.c index 7bf2c0f87dbea4..566e1f37cfed12 100644 --- a/deps/uv/src/unix/linux-syscalls.c +++ b/deps/uv/src/unix/linux-syscalls.c @@ -26,6 +26,13 @@ #include #include +#if defined(__has_feature) +# if __has_feature(memory_sanitizer) +# define MSAN_ACTIVE 1 +# include +# endif +#endif + #if defined(__i386__) # ifndef __NR_socketcall # define __NR_socketcall 102 @@ -310,7 +317,13 @@ int uv__epoll_wait(int epfd, int nevents, int timeout) { #if defined(__NR_epoll_wait) - return syscall(__NR_epoll_wait, epfd, events, nevents, timeout); + int result; + result = syscall(__NR_epoll_wait, epfd, events, nevents, timeout); +#if MSAN_ACTIVE + if (result > 0) + __msan_unpoison(events, sizeof(events[0]) * result); +#endif + return result; #else return errno = ENOSYS, -1; #endif @@ -323,13 +336,19 @@ int uv__epoll_pwait(int epfd, int timeout, uint64_t sigmask) { #if defined(__NR_epoll_pwait) - return syscall(__NR_epoll_pwait, - epfd, - events, - nevents, - timeout, - &sigmask, - sizeof(sigmask)); + int result; + result = syscall(__NR_epoll_pwait, + epfd, + events, + nevents, + timeout, + &sigmask, + sizeof(sigmask)); +#if MSAN_ACTIVE + if (result > 0) + __msan_unpoison(events, sizeof(events[0]) * result); +#endif + return result; #else return errno = ENOSYS, -1; #endif @@ -374,7 +393,13 @@ int uv__inotify_rm_watch(int fd, int32_t wd) { int uv__pipe2(int pipefd[2], int flags) { #if defined(__NR_pipe2) - return syscall(__NR_pipe2, pipefd, flags); + int result; + result = syscall(__NR_pipe2, pipefd, flags); +#if MSAN_ACTIVE + if (!result) + __msan_unpoison(pipefd, sizeof(int[2])); +#endif + return result; #else return errno = ENOSYS, -1; #endif diff --git a/deps/uv/src/unix/process.c b/deps/uv/src/unix/process.c index be283b480d6a23..380f3db1dce7f4 100644 --- a/deps/uv/src/unix/process.c +++ b/deps/uv/src/unix/process.c @@ -280,6 +280,21 @@ static void uv__process_child_init(const uv_process_options_t* options, if (options->flags & UV_PROCESS_DETACHED) setsid(); + /* First duplicate low numbered fds, since it's not safe to duplicate them, + * they could get replaced. Example: swapping stdout and stderr; without + * this fd 2 (stderr) would be duplicated into fd 1, thus making both + * stdout and stderr go to the same fd, which was not the intention. */ + for (fd = 0; fd < stdio_count; fd++) { + use_fd = pipes[fd][1]; + if (use_fd < 0 || use_fd >= fd) + continue; + pipes[fd][1] = fcntl(use_fd, F_DUPFD, stdio_count); + if (pipes[fd][1] == -1) { + uv__write_int(error_fd, -errno); + _exit(127); + } + } + for (fd = 0; fd < stdio_count; fd++) { close_fd = pipes[fd][0]; use_fd = pipes[fd][1]; @@ -304,7 +319,12 @@ static void uv__process_child_init(const uv_process_options_t* options, if (fd == use_fd) uv__cloexec(use_fd, 0); else - dup2(use_fd, fd); + fd = dup2(use_fd, fd); + + if (fd == -1) { + uv__write_int(error_fd, -errno); + _exit(127); + } if (fd <= 2) uv__nonblock(fd, 0); @@ -316,8 +336,8 @@ static void uv__process_child_init(const uv_process_options_t* options, for (fd = 0; fd < stdio_count; fd++) { use_fd = pipes[fd][1]; - if (use_fd >= 0 && fd != use_fd) - close(use_fd); + if (use_fd >= stdio_count) + uv__close(use_fd); } if (options->cwd != NULL && chdir(options->cwd)) { @@ -367,6 +387,7 @@ int uv_spawn(uv_loop_t* loop, int err; int exec_errorno; int i; + int status; assert(options->file != NULL); assert(!(options->flags & ~(UV_PROCESS_DETACHED | @@ -453,11 +474,17 @@ int uv_spawn(uv_loop_t* loop, if (r == 0) ; /* okay, EOF */ - else if (r == sizeof(exec_errorno)) - ; /* okay, read errorno */ - else if (r == -1 && errno == EPIPE) - ; /* okay, got EPIPE */ - else + else if (r == sizeof(exec_errorno)) { + do + err = waitpid(pid, &status, 0); /* okay, read errorno */ + while (err == -1 && errno == EINTR); + assert(err == pid); + } else if (r == -1 && errno == EPIPE) { + do + err = waitpid(pid, &status, 0); /* okay, got EPIPE */ + while (err == -1 && errno == EINTR); + assert(err == pid); + } else abort(); uv__close(signal_pipe[0]); diff --git a/deps/uv/src/unix/stream.c b/deps/uv/src/unix/stream.c index 518a2fce0f2e46..48827b65d36dee 100644 --- a/deps/uv/src/unix/stream.c +++ b/deps/uv/src/unix/stream.c @@ -88,7 +88,12 @@ void uv__stream_init(uv_loop_t* loop, stream->write_queue_size = 0; if (loop->emfile_fd == -1) { - err = uv__open_cloexec("/", O_RDONLY); + err = uv__open_cloexec("/dev/null", O_RDONLY); + if (err < 0) + /* In the rare case that "/dev/null" isn't mounted open "/" + * instead. + */ + err = uv__open_cloexec("/", O_RDONLY); if (err >= 0) loop->emfile_fd = err; } @@ -301,7 +306,7 @@ int uv__stream_try_select(uv_stream_t* stream, int* fd) { if (fds[1] > max_fd) max_fd = fds[1]; - sread_sz = (max_fd + NBBY) / NBBY; + sread_sz = ROUND_UP(max_fd + 1, sizeof(uint32_t) * NBBY) / NBBY; swrite_sz = sread_sz; s = malloc(sizeof(*s) + sread_sz + swrite_sz); diff --git a/deps/uv/src/unix/tty.c b/deps/uv/src/unix/tty.c index b1782df95b2010..7783548a6e987d 100644 --- a/deps/uv/src/unix/tty.c +++ b/deps/uv/src/unix/tty.c @@ -35,10 +35,19 @@ static uv_spinlock_t termios_spinlock = UV_SPINLOCK_INITIALIZER; int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, int fd, int readable) { + uv_handle_type type; int flags; int newfd; int r; + /* File descriptors that refer to files cannot be monitored with epoll. + * That restriction also applies to character devices like /dev/random + * (but obviously not /dev/tty.) + */ + type = uv_guess_handle(fd); + if (type == UV_FILE || type == UV_UNKNOWN_HANDLE) + return -EINVAL; + flags = 0; newfd = -1; @@ -54,7 +63,7 @@ int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, int fd, int readable) { * different struct file, hence changing its properties doesn't affect * other processes. */ - if (isatty(fd)) { + if (type == UV_TTY) { r = uv__open_cloexec("/dev/tty", O_RDWR); if (r < 0) { @@ -237,8 +246,10 @@ uv_handle_type uv_guess_handle(uv_file file) { * critical section when the signal was raised. */ int uv_tty_reset_mode(void) { + int saved_errno; int err; + saved_errno = errno; if (!uv_spinlock_trylock(&termios_spinlock)) return -EBUSY; /* In uv_tty_set_mode(). */ @@ -248,5 +259,7 @@ int uv_tty_reset_mode(void) { err = -errno; uv_spinlock_unlock(&termios_spinlock); + errno = saved_errno; + return err; } diff --git a/deps/uv/src/unix/udp.c b/deps/uv/src/unix/udp.c index 941c0aec6e2f0b..22c2e1388e14ac 100644 --- a/deps/uv/src/unix/udp.c +++ b/deps/uv/src/unix/udp.c @@ -601,40 +601,47 @@ int uv_udp_set_membership(uv_udp_t* handle, } } - -static int uv__setsockopt_maybe_char(uv_udp_t* handle, - int option4, - int option6, - int val) { +static int uv__setsockopt(uv_udp_t* handle, + int option4, + int option6, + const void* val, + size_t size) { int r; -#if defined(__sun) || defined(_AIX) - char arg = val; -#else - int arg = val; -#endif - - if (val < 0 || val > 255) - return -EINVAL; if (handle->flags & UV_HANDLE_IPV6) r = setsockopt(handle->io_watcher.fd, IPPROTO_IPV6, option6, - &arg, - sizeof(arg)); + val, + size); else r = setsockopt(handle->io_watcher.fd, IPPROTO_IP, option4, - &arg, - sizeof(arg)); - + val, + size); if (r) return -errno; return 0; } +static int uv__setsockopt_maybe_char(uv_udp_t* handle, + int option4, + int option6, + int val) { +#if defined(__sun) || defined(_AIX) + char arg = val; +#else + int arg = val; +#endif + + if (val < 0 || val > 255) + return -EINVAL; + + return uv__setsockopt(handle, option4, option6, &arg, sizeof(arg)); +} + int uv_udp_set_broadcast(uv_udp_t* handle, int on) { if (setsockopt(handle->io_watcher.fd, @@ -653,6 +660,20 @@ int uv_udp_set_ttl(uv_udp_t* handle, int ttl) { if (ttl < 1 || ttl > 255) return -EINVAL; +/* + * On Solaris and derivatives such as SmartOS, the length of socket options + * is sizeof(int) for IP_TTL and IPV6_UNICAST_HOPS, + * so hardcode the size of these options on this platform, + * and use the general uv__setsockopt_maybe_char call on other platforms. + */ +#if defined(__sun) + return uv__setsockopt(handle, + IP_TTL, + IPV6_UNICAST_HOPS, + &ttl, + sizeof(ttl)); +#endif /* defined(__sun) */ + return uv__setsockopt_maybe_char(handle, IP_TTL, IPV6_UNICAST_HOPS, @@ -661,6 +682,21 @@ int uv_udp_set_ttl(uv_udp_t* handle, int ttl) { int uv_udp_set_multicast_ttl(uv_udp_t* handle, int ttl) { +/* + * On Solaris and derivatives such as SmartOS, the length of socket options + * is sizeof(int) for IPV6_MULTICAST_HOPS and sizeof(char) for + * IP_MULTICAST_TTL, so hardcode the size of the option in the IPv6 case, + * and use the general uv__setsockopt_maybe_char call otherwise. + */ +#if defined(__sun) + if (handle->flags & UV_HANDLE_IPV6) + return uv__setsockopt(handle, + IP_MULTICAST_TTL, + IPV6_MULTICAST_HOPS, + &ttl, + sizeof(ttl)); +#endif /* defined(__sun) */ + return uv__setsockopt_maybe_char(handle, IP_MULTICAST_TTL, IPV6_MULTICAST_HOPS, @@ -669,6 +705,21 @@ int uv_udp_set_multicast_ttl(uv_udp_t* handle, int ttl) { int uv_udp_set_multicast_loop(uv_udp_t* handle, int on) { +/* + * On Solaris and derivatives such as SmartOS, the length of socket options + * is sizeof(int) for IPV6_MULTICAST_LOOP and sizeof(char) for + * IP_MULTICAST_LOOP, so hardcode the size of the option in the IPv6 case, + * and use the general uv__setsockopt_maybe_char call otherwise. + */ +#if defined(__sun) + if (handle->flags & UV_HANDLE_IPV6) + return uv__setsockopt(handle, + IP_MULTICAST_LOOP, + IPV6_MULTICAST_LOOP, + &on, + sizeof(on)); +#endif /* defined(__sun) */ + return uv__setsockopt_maybe_char(handle, IP_MULTICAST_LOOP, IPV6_MULTICAST_LOOP, diff --git a/deps/uv/src/uv-common.c b/deps/uv/src/uv-common.c index 791c09b4e28e77..02341f8b95d9c0 100644 --- a/deps/uv/src/uv-common.c +++ b/deps/uv/src/uv-common.c @@ -379,15 +379,28 @@ int uv_fs_event_getpath(uv_fs_event_t* handle, char* buffer, size_t* size) { return 0; } +/* The windows implementation does not have the same structure layout as + * the unix implementation (nbufs is not directly inside req but is + * contained in a nested union/struct) so this function locates it. +*/ +static unsigned int* uv__get_nbufs(uv_fs_t* req) { +#ifdef _WIN32 + return &req->fs.info.nbufs; +#else + return &req->nbufs; +#endif +} void uv__fs_scandir_cleanup(uv_fs_t* req) { uv__dirent_t** dents; + unsigned int* nbufs = uv__get_nbufs(req); + dents = req->ptr; - if (req->nbufs > 0 && req->nbufs != (unsigned int) req->result) - req->nbufs--; - for (; req->nbufs < (unsigned int) req->result; req->nbufs++) - free(dents[req->nbufs]); + if (*nbufs > 0 && *nbufs != (unsigned int) req->result) + (*nbufs)--; + for (; *nbufs < (unsigned int) req->result; (*nbufs)++) + free(dents[*nbufs]); } @@ -395,20 +408,22 @@ int uv_fs_scandir_next(uv_fs_t* req, uv_dirent_t* ent) { uv__dirent_t** dents; uv__dirent_t* dent; + unsigned int* nbufs = uv__get_nbufs(req); + dents = req->ptr; /* Free previous entity */ - if (req->nbufs > 0) - free(dents[req->nbufs - 1]); + if (*nbufs > 0) + free(dents[*nbufs - 1]); /* End was already reached */ - if (req->nbufs == (unsigned int) req->result) { + if (*nbufs == (unsigned int) req->result) { free(dents); req->ptr = NULL; return UV_EOF; } - dent = dents[req->nbufs++]; + dent = dents[(*nbufs)++]; ent->name = dent->d_name; #ifdef HAVE_DIRENT_TYPES @@ -522,6 +537,7 @@ void uv_loop_delete(uv_loop_t* loop) { default_loop = default_loop_ptr; err = uv_loop_close(loop); + (void) err; /* Squelch compiler warnings. */ assert(err == 0); if (loop != default_loop) free(loop); diff --git a/deps/uv/src/win/core.c b/deps/uv/src/win/core.c index a101159438341f..115449224f9651 100644 --- a/deps/uv/src/win/core.c +++ b/deps/uv/src/win/core.c @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include diff --git a/deps/uv/src/win/error.c b/deps/uv/src/win/error.c index 5c5514736e8304..a265a272dced19 100644 --- a/deps/uv/src/win/error.c +++ b/deps/uv/src/win/error.c @@ -21,7 +21,6 @@ #include #include -#include #include #include #include diff --git a/deps/uv/src/win/fs-event.c b/deps/uv/src/win/fs-event.c index 7ad99a88b1ebef..640651b6c9634b 100644 --- a/deps/uv/src/win/fs-event.c +++ b/deps/uv/src/win/fs-event.c @@ -20,7 +20,6 @@ */ #include -#include #include #include #include @@ -39,7 +38,8 @@ static void uv_fs_event_queue_readdirchanges(uv_loop_t* loop, assert(handle->dir_handle != INVALID_HANDLE_VALUE); assert(!handle->req_pending); - memset(&(handle->req.overlapped), 0, sizeof(handle->req.overlapped)); + memset(&(handle->req.u.io.overlapped), 0, + sizeof(handle->req.u.io.overlapped)); if (!ReadDirectoryChangesW(handle->dir_handle, handle->buffer, uv_directory_watcher_buffer_size, @@ -53,7 +53,7 @@ static void uv_fs_event_queue_readdirchanges(uv_loop_t* loop, FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, NULL, - &handle->req.overlapped, + &handle->req.u.io.overlapped, NULL)) { /* Make this req pending reporting an error. */ SET_REQ_ERROR(&handle->req, GetLastError()); @@ -232,7 +232,8 @@ int uv_fs_event_start(uv_fs_event_t* handle, uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); } - memset(&(handle->req.overlapped), 0, sizeof(handle->req.overlapped)); + memset(&(handle->req.u.io.overlapped), 0, + sizeof(handle->req.u.io.overlapped)); if (!ReadDirectoryChangesW(handle->dir_handle, handle->buffer, @@ -247,7 +248,7 @@ int uv_fs_event_start(uv_fs_event_t* handle, FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, NULL, - &handle->req.overlapped, + &handle->req.u.io.overlapped, NULL)) { last_error = GetLastError(); goto error; @@ -349,7 +350,7 @@ void uv_process_fs_event_req(uv_loop_t* loop, uv_req_t* req, file_info = (FILE_NOTIFY_INFORMATION*)(handle->buffer + offset); if (REQ_SUCCESS(req)) { - if (req->overlapped.InternalHigh > 0) { + if (req->u.io.overlapped.InternalHigh > 0) { do { file_info = (FILE_NOTIFY_INFORMATION*)((char*)file_info + offset); assert(!filename); diff --git a/deps/uv/src/win/fs.c b/deps/uv/src/win/fs.c index 33bc9da304054f..af7ec74276f995 100644 --- a/deps/uv/src/win/fs.c +++ b/deps/uv/src/win/fs.c @@ -21,7 +21,6 @@ #include #include -#include #include #include #include @@ -161,8 +160,8 @@ INLINE static int fs__capture_path(uv_loop_t* loop, uv_fs_t* req, if (buf_sz == 0) { - req->pathw = NULL; - req->new_pathw = NULL; + req->file.pathw = NULL; + req->fs.info.new_pathw = NULL; req->path = NULL; return 0; } @@ -182,10 +181,10 @@ INLINE static int fs__capture_path(uv_loop_t* loop, uv_fs_t* req, (WCHAR*) pos, pathw_len); assert(r == (DWORD) pathw_len); - req->pathw = (WCHAR*) pos; + req->file.pathw = (WCHAR*) pos; pos += r * sizeof(WCHAR); } else { - req->pathw = NULL; + req->file.pathw = NULL; } if (new_path != NULL) { @@ -196,10 +195,10 @@ INLINE static int fs__capture_path(uv_loop_t* loop, uv_fs_t* req, (WCHAR*) pos, new_pathw_len); assert(r == (DWORD) new_pathw_len); - req->new_pathw = (WCHAR*) pos; + req->fs.info.new_pathw = (WCHAR*) pos; pos += r * sizeof(WCHAR); } else { - req->new_pathw = NULL; + req->fs.info.new_pathw = NULL; } if (!copy_path) { @@ -388,7 +387,7 @@ void fs__open(uv_fs_t* req) { DWORD attributes = 0; HANDLE file; int fd, current_umask; - int flags = req->file_flags; + int flags = req->fs.info.file_flags; /* Obtain the active umask. umask() never fails and returns the previous */ /* umask. */ @@ -450,7 +449,7 @@ void fs__open(uv_fs_t* req) { attributes |= FILE_ATTRIBUTE_NORMAL; if (flags & _O_CREAT) { - if (!((req->mode & ~current_umask) & _S_IWRITE)) { + if (!((req->fs.info.mode & ~current_umask) & _S_IWRITE)) { attributes |= FILE_ATTRIBUTE_READONLY; } } @@ -480,7 +479,7 @@ void fs__open(uv_fs_t* req) { /* Setting this flag makes it possible to open a directory. */ attributes |= FILE_FLAG_BACKUP_SEMANTICS; - file = CreateFileW(req->pathw, + file = CreateFileW(req->file.pathw, access, share, NULL, @@ -512,6 +511,7 @@ void fs__open(uv_fs_t* req) { SET_REQ_WIN32_ERROR(req, GetLastError()); else SET_REQ_WIN32_ERROR(req, UV_UNKNOWN); + CloseHandle(file); return; } @@ -523,7 +523,7 @@ void fs__open(uv_fs_t* req) { } void fs__close(uv_fs_t* req) { - int fd = req->fd; + int fd = req->file.fd; int result; VERIFY_FD(fd, req); @@ -534,8 +534,8 @@ void fs__close(uv_fs_t* req) { void fs__read(uv_fs_t* req) { - int fd = req->fd; - int64_t offset = req->offset; + int fd = req->file.fd; + int64_t offset = req->fs.info.offset; HANDLE handle; OVERLAPPED overlapped, *overlapped_ptr; LARGE_INTEGER offset_; @@ -572,13 +572,13 @@ void fs__read(uv_fs_t* req) { } result = ReadFile(handle, - req->bufs[index].base, - req->bufs[index].len, + req->fs.info.bufs[index].base, + req->fs.info.bufs[index].len, &incremental_bytes, overlapped_ptr); bytes += incremental_bytes; ++index; - } while (result && index < req->nbufs); + } while (result && index < req->fs.info.nbufs); if (result || bytes > 0) { SET_REQ_RESULT(req, bytes); @@ -594,8 +594,8 @@ void fs__read(uv_fs_t* req) { void fs__write(uv_fs_t* req) { - int fd = req->fd; - int64_t offset = req->offset; + int fd = req->file.fd; + int64_t offset = req->fs.info.offset; HANDLE handle; OVERLAPPED overlapped, *overlapped_ptr; LARGE_INTEGER offset_; @@ -630,13 +630,13 @@ void fs__write(uv_fs_t* req) { } result = WriteFile(handle, - req->bufs[index].base, - req->bufs[index].len, + req->fs.info.bufs[index].base, + req->fs.info.bufs[index].len, &incremental_bytes, overlapped_ptr); bytes += incremental_bytes; ++index; - } while (result && index < req->nbufs); + } while (result && index < req->fs.info.nbufs); if (result || bytes > 0) { SET_REQ_RESULT(req, bytes); @@ -647,13 +647,13 @@ void fs__write(uv_fs_t* req) { void fs__rmdir(uv_fs_t* req) { - int result = _wrmdir(req->pathw); + int result = _wrmdir(req->file.pathw); SET_REQ_RESULT(req, result); } void fs__unlink(uv_fs_t* req) { - const WCHAR* pathw = req->pathw; + const WCHAR* pathw = req->file.pathw; HANDLE handle; BY_HANDLE_FILE_INFORMATION info; FILE_DISPOSITION_INFORMATION disposition; @@ -661,7 +661,7 @@ void fs__unlink(uv_fs_t* req) { NTSTATUS status; handle = CreateFileW(pathw, - FILE_READ_ATTRIBUTES | DELETE, + FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | DELETE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, @@ -703,6 +703,24 @@ void fs__unlink(uv_fs_t* req) { } } + if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) { + /* Remove read-only attribute */ + FILE_BASIC_INFORMATION basic = { 0 }; + + basic.FileAttributes = info.dwFileAttributes & ~(FILE_ATTRIBUTE_READONLY); + + status = pNtSetInformationFile(handle, + &iosb, + &basic, + sizeof basic, + FileBasicInformation); + if (!NT_SUCCESS(status)) { + SET_REQ_WIN32_ERROR(req, pRtlNtStatusToDosError(status)); + CloseHandle(handle); + return; + } + } + /* Try to set the delete flag. */ disposition.DeleteFile = TRUE; status = pNtSetInformationFile(handle, @@ -722,7 +740,7 @@ void fs__unlink(uv_fs_t* req) { void fs__mkdir(uv_fs_t* req) { /* TODO: use req->mode. */ - int result = _wmkdir(req->pathw); + int result = _wmkdir(req->file.pathw); SET_REQ_RESULT(req, result); } @@ -740,8 +758,8 @@ void fs__mkdtemp(uv_fs_t* req) { uint64_t v; BOOL released; - len = wcslen(req->pathw); - ep = req->pathw + len; + len = wcslen(req->file.pathw); + ep = req->file.pathw + len; if (len < num_x || wcsncmp(ep - num_x, L"XXXXXX", num_x)) { SET_REQ_UV_ERROR(req, UV_EINVAL, ERROR_INVALID_PARAMETER); return; @@ -766,7 +784,7 @@ void fs__mkdtemp(uv_fs_t* req) { v /= num_chars; } - if (_wmkdir(req->pathw) == 0) { + if (_wmkdir(req->file.pathw) == 0) { len = strlen(req->path); wcstombs((char*) req->path + len - num_x, ep - num_x, num_x); SET_REQ_RESULT(req, 0); @@ -810,7 +828,7 @@ void fs__scandir(uv_fs_t* req) { /* Open the directory. */ dir_handle = - CreateFileW(req->pathw, + CreateFileW(req->file.pathw, FILE_LIST_DIRECTORY | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, @@ -956,7 +974,7 @@ void fs__scandir(uv_fs_t* req) { SET_REQ_RESULT(req, dirents_used); /* `nbufs` will be used as index by uv_fs_scandir_next. */ - req->nbufs = 0; + req->fs.info.nbufs = 0; return; @@ -1125,7 +1143,7 @@ INLINE static void fs__stat_impl(uv_fs_t* req, int do_lstat) { flags |= FILE_FLAG_OPEN_REPARSE_POINT; } - handle = CreateFileW(req->pathw, + handle = CreateFileW(req->file.pathw, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, @@ -1159,19 +1177,19 @@ INLINE static void fs__stat_impl(uv_fs_t* req, int do_lstat) { static void fs__stat(uv_fs_t* req) { - fs__stat_prepare_path(req->pathw); + fs__stat_prepare_path(req->file.pathw); fs__stat_impl(req, 0); } static void fs__lstat(uv_fs_t* req) { - fs__stat_prepare_path(req->pathw); + fs__stat_prepare_path(req->file.pathw); fs__stat_impl(req, 1); } static void fs__fstat(uv_fs_t* req) { - int fd = req->fd; + int fd = req->file.fd; HANDLE handle; VERIFY_FD(fd, req); @@ -1194,7 +1212,7 @@ static void fs__fstat(uv_fs_t* req) { static void fs__rename(uv_fs_t* req) { - if (!MoveFileExW(req->pathw, req->new_pathw, MOVEFILE_REPLACE_EXISTING)) { + if (!MoveFileExW(req->file.pathw, req->fs.info.new_pathw, MOVEFILE_REPLACE_EXISTING)) { SET_REQ_WIN32_ERROR(req, GetLastError()); return; } @@ -1204,7 +1222,7 @@ static void fs__rename(uv_fs_t* req) { INLINE static void fs__sync_impl(uv_fs_t* req) { - int fd = req->fd; + int fd = req->file.fd; int result; VERIFY_FD(fd, req); @@ -1229,7 +1247,7 @@ static void fs__fdatasync(uv_fs_t* req) { static void fs__ftruncate(uv_fs_t* req) { - int fd = req->fd; + int fd = req->file.fd; HANDLE handle; NTSTATUS status; IO_STATUS_BLOCK io_status; @@ -1239,7 +1257,7 @@ static void fs__ftruncate(uv_fs_t* req) { handle = uv__get_osfhandle(fd); - eof_info.EndOfFile.QuadPart = req->offset; + eof_info.EndOfFile.QuadPart = req->fs.info.offset; status = pNtSetInformationFile(handle, &io_status, @@ -1256,9 +1274,9 @@ static void fs__ftruncate(uv_fs_t* req) { static void fs__sendfile(uv_fs_t* req) { - int fd_in = req->fd, fd_out = req->fd_out; - size_t length = req->bufsml[0].len; - int64_t offset = req->offset; + int fd_in = req->file.fd, fd_out = req->fs.info.fd_out; + size_t length = req->fs.info.bufsml[0].len; + int64_t offset = req->fs.info.offset; const size_t max_buf_size = 65536; size_t buf_size = length < max_buf_size ? length : max_buf_size; int n, result = 0; @@ -1303,32 +1321,39 @@ static void fs__sendfile(uv_fs_t* req) { static void fs__access(uv_fs_t* req) { - DWORD attr = GetFileAttributesW(req->pathw); + DWORD attr = GetFileAttributesW(req->file.pathw); if (attr == INVALID_FILE_ATTRIBUTES) { SET_REQ_WIN32_ERROR(req, GetLastError()); return; } - if ((req->flags & W_OK) && - ((attr & FILE_ATTRIBUTE_READONLY) || - (attr & FILE_ATTRIBUTE_DIRECTORY))) { + /* + * Access is possible if + * - write access wasn't requested, + * - or the file isn't read-only, + * - or it's a directory. + * (Directories cannot be read-only on Windows.) + */ + if (!(req->flags & W_OK) || + !(attr & FILE_ATTRIBUTE_READONLY) || + (attr & FILE_ATTRIBUTE_DIRECTORY)) { + SET_REQ_RESULT(req, 0); + } else { SET_REQ_WIN32_ERROR(req, UV_EPERM); - return; } - SET_REQ_RESULT(req, 0); } static void fs__chmod(uv_fs_t* req) { - int result = _wchmod(req->pathw, req->mode); + int result = _wchmod(req->file.pathw, req->fs.info.mode); SET_REQ_RESULT(req, result); } static void fs__fchmod(uv_fs_t* req) { - int fd = req->fd; + int fd = req->file.fd; HANDLE handle; NTSTATUS nt_status; IO_STATUS_BLOCK io_status; @@ -1349,7 +1374,7 @@ static void fs__fchmod(uv_fs_t* req) { return; } - if (req->mode & _S_IWRITE) { + if (req->fs.info.mode & _S_IWRITE) { file_info.FileAttributes &= ~FILE_ATTRIBUTE_READONLY; } else { file_info.FileAttributes |= FILE_ATTRIBUTE_READONLY; @@ -1387,7 +1412,7 @@ INLINE static int fs__utime_handle(HANDLE handle, double atime, double mtime) { static void fs__utime(uv_fs_t* req) { HANDLE handle; - handle = CreateFileW(req->pathw, + handle = CreateFileW(req->file.pathw, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, @@ -1400,7 +1425,7 @@ static void fs__utime(uv_fs_t* req) { return; } - if (fs__utime_handle(handle, req->atime, req->mtime) != 0) { + if (fs__utime_handle(handle, req->fs.time.atime, req->fs.time.mtime) != 0) { SET_REQ_WIN32_ERROR(req, GetLastError()); CloseHandle(handle); return; @@ -1413,7 +1438,7 @@ static void fs__utime(uv_fs_t* req) { static void fs__futime(uv_fs_t* req) { - int fd = req->fd; + int fd = req->file.fd; HANDLE handle; VERIFY_FD(fd, req); @@ -1424,7 +1449,7 @@ static void fs__futime(uv_fs_t* req) { return; } - if (fs__utime_handle(handle, req->atime, req->mtime) != 0) { + if (fs__utime_handle(handle, req->fs.time.atime, req->fs.time.mtime) != 0) { SET_REQ_WIN32_ERROR(req, GetLastError()); return; } @@ -1434,7 +1459,7 @@ static void fs__futime(uv_fs_t* req) { static void fs__link(uv_fs_t* req) { - DWORD r = CreateHardLinkW(req->new_pathw, req->pathw, NULL); + DWORD r = CreateHardLinkW(req->fs.info.new_pathw, req->file.pathw, NULL); if (r == 0) { SET_REQ_WIN32_ERROR(req, GetLastError()); } else { @@ -1614,9 +1639,9 @@ static void fs__create_junction(uv_fs_t* req, const WCHAR* path, static void fs__symlink(uv_fs_t* req) { - WCHAR* pathw = req->pathw; - WCHAR* new_pathw = req->new_pathw; - int flags = req->file_flags; + WCHAR* pathw = req->file.pathw; + WCHAR* new_pathw = req->fs.info.new_pathw; + int flags = req->fs.info.file_flags; int result; @@ -1640,7 +1665,7 @@ static void fs__symlink(uv_fs_t* req) { static void fs__readlink(uv_fs_t* req) { HANDLE handle; - handle = CreateFileW(req->pathw, + handle = CreateFileW(req->file.pathw, 0, 0, NULL, @@ -1739,14 +1764,14 @@ void uv_fs_req_cleanup(uv_fs_t* req) { return; if (req->flags & UV_FS_FREE_PATHS) - free(req->pathw); + free(req->file.pathw); if (req->flags & UV_FS_FREE_PTR) free(req->ptr); req->path = NULL; - req->pathw = NULL; - req->new_pathw = NULL; + req->file.pathw = NULL; + req->fs.info.new_pathw = NULL; req->ptr = NULL; req->flags |= UV_FS_CLEANEDUP; @@ -1764,8 +1789,8 @@ int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, return uv_translate_sys_error(err); } - req->file_flags = flags; - req->mode = mode; + req->fs.info.file_flags = flags; + req->fs.info.mode = mode; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -1779,7 +1804,7 @@ int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_CLOSE, cb); - req->fd = fd; + req->file.fd = fd; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -1800,19 +1825,19 @@ int uv_fs_read(uv_loop_t* loop, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_READ, cb); - req->fd = fd; + req->file.fd = fd; - req->nbufs = nbufs; - req->bufs = req->bufsml; - if (nbufs > ARRAY_SIZE(req->bufsml)) - req->bufs = malloc(nbufs * sizeof(*bufs)); + req->fs.info.nbufs = nbufs; + req->fs.info.bufs = req->fs.info.bufsml; + if (nbufs > ARRAY_SIZE(req->fs.info.bufsml)) + req->fs.info.bufs = malloc(nbufs * sizeof(*bufs)); - if (req->bufs == NULL) + if (req->fs.info.bufs == NULL) return UV_ENOMEM; - memcpy(req->bufs, bufs, nbufs * sizeof(*bufs)); + memcpy(req->fs.info.bufs, bufs, nbufs * sizeof(*bufs)); - req->offset = offset; + req->fs.info.offset = offset; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -1833,19 +1858,19 @@ int uv_fs_write(uv_loop_t* loop, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_WRITE, cb); - req->fd = fd; + req->file.fd = fd; - req->nbufs = nbufs; - req->bufs = req->bufsml; - if (nbufs > ARRAY_SIZE(req->bufsml)) - req->bufs = malloc(nbufs * sizeof(*bufs)); + req->fs.info.nbufs = nbufs; + req->fs.info.bufs = req->fs.info.bufsml; + if (nbufs > ARRAY_SIZE(req->fs.info.bufsml)) + req->fs.info.bufs = malloc(nbufs * sizeof(*bufs)); - if (req->bufs == NULL) + if (req->fs.info.bufs == NULL) return UV_ENOMEM; - memcpy(req->bufs, bufs, nbufs * sizeof(*bufs)); + memcpy(req->fs.info.bufs, bufs, nbufs * sizeof(*bufs)); - req->offset = offset; + req->fs.info.offset = offset; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -1889,7 +1914,7 @@ int uv_fs_mkdir(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, return uv_translate_sys_error(err); } - req->mode = mode; + req->fs.info.mode = mode; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -1952,7 +1977,7 @@ int uv_fs_scandir(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, return uv_translate_sys_error(err); } - req->file_flags = flags; + req->fs.info.file_flags = flags; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -1996,7 +2021,7 @@ int uv_fs_symlink(uv_loop_t* loop, uv_fs_t* req, const char* path, return uv_translate_sys_error(err); } - req->file_flags = flags; + req->fs.info.file_flags = flags; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2106,7 +2131,7 @@ int uv_fs_lstat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) { int uv_fs_fstat(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_FSTAT, cb); - req->fd = fd; + req->file.fd = fd; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2141,7 +2166,7 @@ int uv_fs_rename(uv_loop_t* loop, uv_fs_t* req, const char* path, int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_FSYNC, cb); - req->fd = fd; + req->file.fd = fd; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2155,7 +2180,7 @@ int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) { int uv_fs_fdatasync(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_FDATASYNC, cb); - req->fd = fd; + req->file.fd = fd; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2171,8 +2196,8 @@ int uv_fs_ftruncate(uv_loop_t* loop, uv_fs_t* req, uv_file fd, int64_t offset, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_FTRUNCATE, cb); - req->fd = fd; - req->offset = offset; + req->file.fd = fd; + req->fs.info.offset = offset; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2189,10 +2214,10 @@ int uv_fs_sendfile(uv_loop_t* loop, uv_fs_t* req, uv_file fd_out, uv_file fd_in, int64_t in_offset, size_t length, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_SENDFILE, cb); - req->fd = fd_in; - req->fd_out = fd_out; - req->offset = in_offset; - req->bufsml[0].len = length; + req->file.fd = fd_in; + req->fs.info.fd_out = fd_out; + req->fs.info.offset = in_offset; + req->fs.info.bufsml[0].len = length; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2240,7 +2265,7 @@ int uv_fs_chmod(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, return uv_translate_sys_error(err); } - req->mode = mode; + req->fs.info.mode = mode; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2256,8 +2281,8 @@ int uv_fs_fchmod(uv_loop_t* loop, uv_fs_t* req, uv_file fd, int mode, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_FCHMOD, cb); - req->fd = fd; - req->mode = mode; + req->file.fd = fd; + req->fs.info.mode = mode; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2280,8 +2305,8 @@ int uv_fs_utime(uv_loop_t* loop, uv_fs_t* req, const char* path, double atime, return uv_translate_sys_error(err); } - req->atime = atime; - req->mtime = mtime; + req->fs.time.atime = atime; + req->fs.time.mtime = mtime; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2297,9 +2322,9 @@ int uv_fs_futime(uv_loop_t* loop, uv_fs_t* req, uv_file fd, double atime, double mtime, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_FUTIME, cb); - req->fd = fd; - req->atime = atime; - req->mtime = mtime; + req->file.fd = fd; + req->fs.time.atime = atime; + req->fs.time.mtime = mtime; if (cb) { QUEUE_FS_TP_JOB(loop, req); diff --git a/deps/uv/src/win/getaddrinfo.c b/deps/uv/src/win/getaddrinfo.c index f103f5fbd3418a..f3802cd5829208 100644 --- a/deps/uv/src/win/getaddrinfo.c +++ b/deps/uv/src/win/getaddrinfo.c @@ -20,7 +20,6 @@ */ #include -#include #include "uv.h" #include "internal.h" diff --git a/deps/uv/src/win/getnameinfo.c b/deps/uv/src/win/getnameinfo.c index b1d045c79bd9db..66b64b883248e3 100644 --- a/deps/uv/src/win/getnameinfo.c +++ b/deps/uv/src/win/getnameinfo.c @@ -20,7 +20,6 @@ */ #include -#include #include #include "uv.h" diff --git a/deps/uv/src/win/pipe.c b/deps/uv/src/win/pipe.c index 57fab065aa346b..5a0e5420847b12 100644 --- a/deps/uv/src/win/pipe.c +++ b/deps/uv/src/win/pipe.c @@ -95,15 +95,15 @@ int uv_pipe_init(uv_loop_t* loop, uv_pipe_t* handle, int ipc) { handle->reqs_pending = 0; handle->handle = INVALID_HANDLE_VALUE; handle->name = NULL; - handle->ipc_pid = 0; - handle->remaining_ipc_rawdata_bytes = 0; - QUEUE_INIT(&handle->pending_ipc_info.queue); - handle->pending_ipc_info.queue_len = 0; + handle->pipe.conn.ipc_pid = 0; + handle->pipe.conn.remaining_ipc_rawdata_bytes = 0; + QUEUE_INIT(&handle->pipe.conn.pending_ipc_info.queue); + handle->pipe.conn.pending_ipc_info.queue_len = 0; handle->ipc = ipc; - handle->non_overlapped_writes_tail = NULL; - handle->readfile_thread = NULL; + handle->pipe.conn.non_overlapped_writes_tail = NULL; + handle->pipe.conn.readfile_thread = NULL; - uv_req_init(loop, (uv_req_t*) &handle->ipc_header_write_req); + uv_req_init(loop, (uv_req_t*) &handle->pipe.conn.ipc_header_write_req); return 0; } @@ -112,11 +112,11 @@ int uv_pipe_init(uv_loop_t* loop, uv_pipe_t* handle, int ipc) { static void uv_pipe_connection_init(uv_pipe_t* handle) { uv_connection_init((uv_stream_t*) handle); handle->read_req.data = handle; - handle->eof_timer = NULL; + handle->pipe.conn.eof_timer = NULL; assert(!(handle->flags & UV_HANDLE_PIPESERVER)); if (pCancelSynchronousIo && handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE) { - uv_mutex_init(&handle->readfile_mutex); + uv_mutex_init(&handle->pipe.conn.readfile_mutex); handle->flags |= UV_HANDLE_PIPE_READ_CANCELABLE; } } @@ -330,16 +330,16 @@ void uv_pipe_endgame(uv_loop_t* loop, uv_pipe_t* handle) { if (handle->flags & UV_HANDLE_PIPE_READ_CANCELABLE) { handle->flags &= ~UV_HANDLE_PIPE_READ_CANCELABLE; - uv_mutex_destroy(&handle->readfile_mutex); + uv_mutex_destroy(&handle->pipe.conn.readfile_mutex); } if ((handle->flags & UV_HANDLE_CONNECTION) && - handle->shutdown_req != NULL && - handle->write_reqs_pending == 0) { - req = handle->shutdown_req; + handle->stream.conn.shutdown_req != NULL && + handle->stream.conn.write_reqs_pending == 0) { + req = handle->stream.conn.shutdown_req; /* Clear the shutdown_req field so we don't go here again. */ - handle->shutdown_req = NULL; + handle->stream.conn.shutdown_req = NULL; if (handle->flags & UV__HANDLE_CLOSING) { UNREGISTER_HANDLE_REQ(loop, handle, req); @@ -408,11 +408,11 @@ void uv_pipe_endgame(uv_loop_t* loop, uv_pipe_t* handle) { if (handle->flags & UV_HANDLE_CONNECTION) { /* Free pending sockets */ - while (!QUEUE_EMPTY(&handle->pending_ipc_info.queue)) { + while (!QUEUE_EMPTY(&handle->pipe.conn.pending_ipc_info.queue)) { QUEUE* q; SOCKET socket; - q = QUEUE_HEAD(&handle->pending_ipc_info.queue); + q = QUEUE_HEAD(&handle->pipe.conn.pending_ipc_info.queue); QUEUE_REMOVE(q); item = QUEUE_DATA(q, uv__ipc_queue_item_t, member); @@ -428,7 +428,7 @@ void uv_pipe_endgame(uv_loop_t* loop, uv_pipe_t* handle) { if (socket != INVALID_SOCKET) closesocket(socket); } - handle->pending_ipc_info.queue_len = 0; + handle->pipe.conn.pending_ipc_info.queue_len = 0; if (handle->flags & UV_HANDLE_EMULATE_IOCP) { if (handle->read_req.wait_handle != INVALID_HANDLE_VALUE) { @@ -443,9 +443,9 @@ void uv_pipe_endgame(uv_loop_t* loop, uv_pipe_t* handle) { } if (handle->flags & UV_HANDLE_PIPESERVER) { - assert(handle->accept_reqs); - free(handle->accept_reqs); - handle->accept_reqs = NULL; + assert(handle->pipe.serv.accept_reqs); + free(handle->pipe.serv.accept_reqs); + handle->pipe.serv.accept_reqs = NULL; } uv__handle_close(handle); @@ -454,7 +454,7 @@ void uv_pipe_endgame(uv_loop_t* loop, uv_pipe_t* handle) { void uv_pipe_pending_instances(uv_pipe_t* handle, int count) { - handle->pending_instances = count; + handle->pipe.serv.pending_instances = count; handle->flags |= UV_HANDLE_PIPESERVER; } @@ -474,17 +474,17 @@ int uv_pipe_bind(uv_pipe_t* handle, const char* name) { } if (!(handle->flags & UV_HANDLE_PIPESERVER)) { - handle->pending_instances = default_pending_pipe_instances; + handle->pipe.serv.pending_instances = default_pending_pipe_instances; } - handle->accept_reqs = (uv_pipe_accept_t*) - malloc(sizeof(uv_pipe_accept_t) * handle->pending_instances); - if (!handle->accept_reqs) { + handle->pipe.serv.accept_reqs = (uv_pipe_accept_t*) + malloc(sizeof(uv_pipe_accept_t) * handle->pipe.serv.pending_instances); + if (!handle->pipe.serv.accept_reqs) { uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); } - for (i = 0; i < handle->pending_instances; i++) { - req = &handle->accept_reqs[i]; + for (i = 0; i < handle->pipe.serv.pending_instances; i++) { + req = &handle->pipe.serv.accept_reqs[i]; uv_req_init(loop, (uv_req_t*) req); req->type = UV_ACCEPT; req->data = handle; @@ -508,13 +508,13 @@ int uv_pipe_bind(uv_pipe_t* handle, const char* name) { * Attempt to create the first pipe with FILE_FLAG_FIRST_PIPE_INSTANCE. * If this fails then there's already a pipe server for the given pipe name. */ - handle->accept_reqs[0].pipeHandle = CreateNamedPipeW(handle->name, + handle->pipe.serv.accept_reqs[0].pipeHandle = CreateNamedPipeW(handle->name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, NULL); - if (handle->accept_reqs[0].pipeHandle == INVALID_HANDLE_VALUE) { + if (handle->pipe.serv.accept_reqs[0].pipeHandle == INVALID_HANDLE_VALUE) { err = GetLastError(); if (err == ERROR_ACCESS_DENIED) { err = WSAEADDRINUSE; /* Translates to UV_EADDRINUSE. */ @@ -524,12 +524,15 @@ int uv_pipe_bind(uv_pipe_t* handle, const char* name) { goto error; } - if (uv_set_pipe_handle(loop, handle, handle->accept_reqs[0].pipeHandle, 0)) { + if (uv_set_pipe_handle(loop, + handle, + handle->pipe.serv.accept_reqs[0].pipeHandle, + 0)) { err = GetLastError(); goto error; } - handle->pending_accepts = NULL; + handle->pipe.serv.pending_accepts = NULL; handle->flags |= UV_HANDLE_PIPESERVER; handle->flags |= UV_HANDLE_BOUND; @@ -541,9 +544,9 @@ int uv_pipe_bind(uv_pipe_t* handle, const char* name) { handle->name = NULL; } - if (handle->accept_reqs[0].pipeHandle != INVALID_HANDLE_VALUE) { - CloseHandle(handle->accept_reqs[0].pipeHandle); - handle->accept_reqs[0].pipeHandle = INVALID_HANDLE_VALUE; + if (handle->pipe.serv.accept_reqs[0].pipeHandle != INVALID_HANDLE_VALUE) { + CloseHandle(handle->pipe.serv.accept_reqs[0].pipeHandle); + handle->pipe.serv.accept_reqs[0].pipeHandle = INVALID_HANDLE_VALUE; } return uv_translate_sys_error(err); @@ -677,15 +680,15 @@ void uv__pipe_pause_read(uv_pipe_t* handle) { any access to a NamedPipe to deadlock if any process has called ReadFile */ HANDLE h; - uv_mutex_lock(&handle->readfile_mutex); - h = handle->readfile_thread; + uv_mutex_lock(&handle->pipe.conn.readfile_mutex); + h = handle->pipe.conn.readfile_thread; while (h) { /* spinlock: we expect this to finish quickly, or we are probably about to deadlock anyways (in the kernel), so it doesn't matter */ pCancelSynchronousIo(h); SwitchToThread(); /* yield thread control briefly */ - h = handle->readfile_thread; + h = handle->pipe.conn.readfile_thread; } } } @@ -693,7 +696,7 @@ void uv__pipe_pause_read(uv_pipe_t* handle) { void uv__pipe_unpause_read(uv_pipe_t* handle) { if (handle->flags & UV_HANDLE_PIPE_READ_CANCELABLE) { - uv_mutex_unlock(&handle->readfile_mutex); + uv_mutex_unlock(&handle->pipe.conn.readfile_mutex); } } @@ -719,11 +722,11 @@ void uv_pipe_cleanup(uv_loop_t* loop, uv_pipe_t* handle) { } if (handle->flags & UV_HANDLE_PIPESERVER) { - for (i = 0; i < handle->pending_instances; i++) { - pipeHandle = handle->accept_reqs[i].pipeHandle; + for (i = 0; i < handle->pipe.serv.pending_instances; i++) { + pipeHandle = handle->pipe.serv.accept_reqs[i].pipeHandle; if (pipeHandle != INVALID_HANDLE_VALUE) { CloseHandle(pipeHandle); - handle->accept_reqs[i].pipeHandle = INVALID_HANDLE_VALUE; + handle->pipe.serv.accept_reqs[i].pipeHandle = INVALID_HANDLE_VALUE; } } } @@ -796,9 +799,9 @@ static void uv_pipe_queue_accept(uv_loop_t* loop, uv_pipe_t* handle, assert(req->pipeHandle != INVALID_HANDLE_VALUE); /* Prepare the overlapped structure. */ - memset(&(req->overlapped), 0, sizeof(req->overlapped)); + memset(&(req->u.io.overlapped), 0, sizeof(req->u.io.overlapped)); - if (!ConnectNamedPipe(req->pipeHandle, &req->overlapped) && + if (!ConnectNamedPipe(req->pipeHandle, &req->u.io.overlapped) && GetLastError() != ERROR_IO_PENDING) { if (GetLastError() == ERROR_PIPE_CONNECTED) { SET_REQ_SUCCESS(req); @@ -826,14 +829,14 @@ int uv_pipe_accept(uv_pipe_t* server, uv_stream_t* client) { int err; if (server->ipc) { - if (QUEUE_EMPTY(&server->pending_ipc_info.queue)) { + if (QUEUE_EMPTY(&server->pipe.conn.pending_ipc_info.queue)) { /* No valid pending sockets. */ return WSAEWOULDBLOCK; } - q = QUEUE_HEAD(&server->pending_ipc_info.queue); + q = QUEUE_HEAD(&server->pipe.conn.pending_ipc_info.queue); QUEUE_REMOVE(q); - server->pending_ipc_info.queue_len--; + server->pipe.conn.pending_ipc_info.queue_len--; item = QUEUE_DATA(q, uv__ipc_queue_item_t, member); err = uv_tcp_import((uv_tcp_t*)client, @@ -849,7 +852,7 @@ int uv_pipe_accept(uv_pipe_t* server, uv_stream_t* client) { /* Find a connection instance that has been connected, but not yet */ /* accepted. */ - req = server->pending_accepts; + req = server->pipe.serv.pending_accepts; if (!req) { /* No valid connections found, so we error out. */ @@ -862,7 +865,7 @@ int uv_pipe_accept(uv_pipe_t* server, uv_stream_t* client) { pipe_client->flags |= UV_HANDLE_READABLE | UV_HANDLE_WRITABLE; /* Prepare the req to pick up a new connection */ - server->pending_accepts = req->next_pending; + server->pipe.serv.pending_accepts = req->next_pending; req->next_pending = NULL; req->pipeHandle = INVALID_HANDLE_VALUE; @@ -881,7 +884,7 @@ int uv_pipe_listen(uv_pipe_t* handle, int backlog, uv_connection_cb cb) { int i; if (handle->flags & UV_HANDLE_LISTENING) { - handle->connection_cb = cb; + handle->stream.serv.connection_cb = cb; } if (!(handle->flags & UV_HANDLE_BOUND)) { @@ -898,13 +901,13 @@ int uv_pipe_listen(uv_pipe_t* handle, int backlog, uv_connection_cb cb) { handle->flags |= UV_HANDLE_LISTENING; INCREASE_ACTIVE_COUNT(loop, handle); - handle->connection_cb = cb; + handle->stream.serv.connection_cb = cb; /* First pipe handle should have already been created in uv_pipe_bind */ - assert(handle->accept_reqs[0].pipeHandle != INVALID_HANDLE_VALUE); + assert(handle->pipe.serv.accept_reqs[0].pipeHandle != INVALID_HANDLE_VALUE); - for (i = 0; i < handle->pending_instances; i++) { - uv_pipe_queue_accept(loop, handle, &handle->accept_reqs[i], i == 0); + for (i = 0; i < handle->pipe.serv.pending_instances; i++) { + uv_pipe_queue_accept(loop, handle, &handle->pipe.serv.accept_reqs[i], i == 0); } return 0; @@ -919,7 +922,7 @@ static DWORD WINAPI uv_pipe_zero_readfile_thread_proc(void* parameter) { uv_loop_t* loop = handle->loop; HANDLE hThread = NULL; DWORD err; - uv_mutex_t *m = &handle->readfile_mutex; + uv_mutex_t *m = &handle->pipe.conn.readfile_mutex; assert(req != NULL); assert(req->type == UV_READ); @@ -930,7 +933,7 @@ static DWORD WINAPI uv_pipe_zero_readfile_thread_proc(void* parameter) { if (DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &hThread, 0, TRUE, DUPLICATE_SAME_ACCESS)) { - handle->readfile_thread = hThread; + handle->pipe.conn.readfile_thread = hThread; } else { hThread = NULL; } @@ -948,10 +951,10 @@ static DWORD WINAPI uv_pipe_zero_readfile_thread_proc(void* parameter) { handle->flags & UV_HANDLE_PIPE_READ_CANCELABLE) { if (handle->flags & UV_HANDLE_READING) { /* just a brief break to do something else */ - handle->readfile_thread = NULL; + handle->pipe.conn.readfile_thread = NULL; /* resume after it is finished */ uv_mutex_lock(m); - handle->readfile_thread = hThread; + handle->pipe.conn.readfile_thread = hThread; uv_mutex_unlock(m); goto restart_readfile; } else { @@ -960,9 +963,9 @@ static DWORD WINAPI uv_pipe_zero_readfile_thread_proc(void* parameter) { } } if (hThread) { - assert(hThread == handle->readfile_thread); + assert(hThread == handle->pipe.conn.readfile_thread); /* mutex does not control clearing readfile_thread */ - handle->readfile_thread = NULL; + handle->pipe.conn.readfile_thread = NULL; uv_mutex_lock(m); /* only when we hold the mutex lock is it safe to open or close the handle */ @@ -1017,9 +1020,9 @@ static void CALLBACK post_completion_read_wait(void* context, BOOLEAN timed_out) assert(!timed_out); if (!PostQueuedCompletionStatus(handle->loop->iocp, - req->overlapped.InternalHigh, + req->u.io.overlapped.InternalHigh, 0, - &req->overlapped)) { + &req->u.io.overlapped)) { uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus"); } } @@ -1036,9 +1039,9 @@ static void CALLBACK post_completion_write_wait(void* context, BOOLEAN timed_out assert(!timed_out); if (!PostQueuedCompletionStatus(handle->loop->iocp, - req->overlapped.InternalHigh, + req->u.io.overlapped.InternalHigh, 0, - &req->overlapped)) { + &req->u.io.overlapped)) { uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus"); } } @@ -1064,9 +1067,9 @@ static void uv_pipe_queue_read(uv_loop_t* loop, uv_pipe_t* handle) { goto error; } } else { - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); if (handle->flags & UV_HANDLE_EMULATE_IOCP) { - req->overlapped.hEvent = (HANDLE) ((uintptr_t) req->event_handle | 1); + req->u.io.overlapped.hEvent = (HANDLE) ((uintptr_t) req->event_handle | 1); } /* Do 0-read */ @@ -1074,7 +1077,7 @@ static void uv_pipe_queue_read(uv_loop_t* loop, uv_pipe_t* handle) { &uv_zero_, 0, NULL, - &req->overlapped); + &req->u.io.overlapped); if (!result && GetLastError() != ERROR_IO_PENDING) { /* Make this req pending reporting an error. */ @@ -1091,7 +1094,7 @@ static void uv_pipe_queue_read(uv_loop_t* loop, uv_pipe_t* handle) { } if (req->wait_handle == INVALID_HANDLE_VALUE) { if (!RegisterWaitForSingleObject(&req->wait_handle, - req->overlapped.hEvent, post_completion_read_wait, (void*) req, + req->u.io.overlapped.hEvent, post_completion_read_wait, (void*) req, INFINITE, WT_EXECUTEINWAITTHREAD)) { SET_REQ_ERROR(req, GetLastError()); goto error; @@ -1135,14 +1138,14 @@ int uv_pipe_read_start(uv_pipe_t* handle, static void uv_insert_non_overlapped_write_req(uv_pipe_t* handle, uv_write_t* req) { req->next_req = NULL; - if (handle->non_overlapped_writes_tail) { + if (handle->pipe.conn.non_overlapped_writes_tail) { req->next_req = - handle->non_overlapped_writes_tail->next_req; - handle->non_overlapped_writes_tail->next_req = (uv_req_t*)req; - handle->non_overlapped_writes_tail = req; + handle->pipe.conn.non_overlapped_writes_tail->next_req; + handle->pipe.conn.non_overlapped_writes_tail->next_req = (uv_req_t*)req; + handle->pipe.conn.non_overlapped_writes_tail = req; } else { req->next_req = (uv_req_t*)req; - handle->non_overlapped_writes_tail = req; + handle->pipe.conn.non_overlapped_writes_tail = req; } } @@ -1150,13 +1153,13 @@ static void uv_insert_non_overlapped_write_req(uv_pipe_t* handle, static uv_write_t* uv_remove_non_overlapped_write_req(uv_pipe_t* handle) { uv_write_t* req; - if (handle->non_overlapped_writes_tail) { - req = (uv_write_t*)handle->non_overlapped_writes_tail->next_req; + if (handle->pipe.conn.non_overlapped_writes_tail) { + req = (uv_write_t*)handle->pipe.conn.non_overlapped_writes_tail->next_req; - if (req == handle->non_overlapped_writes_tail) { - handle->non_overlapped_writes_tail = NULL; + if (req == handle->pipe.conn.non_overlapped_writes_tail) { + handle->pipe.conn.non_overlapped_writes_tail = NULL; } else { - handle->non_overlapped_writes_tail->next_req = + handle->pipe.conn.non_overlapped_writes_tail->next_req = req->next_req; } @@ -1213,7 +1216,7 @@ static int uv_pipe_write_impl(uv_loop_t* loop, req->ipc_header = 0; req->event_handle = NULL; req->wait_handle = INVALID_HANDLE_VALUE; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); if (handle->ipc) { assert(!(handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE)); @@ -1223,7 +1226,7 @@ static int uv_pipe_write_impl(uv_loop_t* loop, if (send_handle) { tcp_send_handle = (uv_tcp_t*)send_handle; - err = uv_tcp_duplicate_socket(tcp_send_handle, handle->ipc_pid, + err = uv_tcp_duplicate_socket(tcp_send_handle, handle->pipe.conn.ipc_pid, &ipc_frame.socket_info_ex.socket_info); if (err) { return err; @@ -1255,8 +1258,8 @@ static int uv_pipe_write_impl(uv_loop_t* loop, * Try to use the preallocated write req if it's available. * Otherwise allocate a new one. */ - if (handle->ipc_header_write_req.type != UV_WRITE) { - ipc_header_req = (uv_write_t*)&handle->ipc_header_write_req; + if (handle->pipe.conn.ipc_header_write_req.type != UV_WRITE) { + ipc_header_req = (uv_write_t*)&handle->pipe.conn.ipc_header_write_req; } else { ipc_header_req = (uv_write_t*)malloc(sizeof(uv_write_t)); if (!ipc_header_req) { @@ -1272,12 +1275,13 @@ static int uv_pipe_write_impl(uv_loop_t* loop, } /* Write the header or the whole frame. */ - memset(&ipc_header_req->overlapped, 0, sizeof(ipc_header_req->overlapped)); + memset(&ipc_header_req->u.io.overlapped, 0, + sizeof(ipc_header_req->u.io.overlapped)); /* Using overlapped IO, but wait for completion before returning. This write is blocking because ipc_frame is on stack. */ - ipc_header_req->overlapped.hEvent = CreateEvent(NULL, 1, 0, NULL); - if (!ipc_header_req->overlapped.hEvent) { + ipc_header_req->u.io.overlapped.hEvent = CreateEvent(NULL, 1, 0, NULL); + if (!ipc_header_req->u.io.overlapped.hEvent) { uv_fatal_error(GetLastError(), "CreateEvent"); } @@ -1286,29 +1290,29 @@ static int uv_pipe_write_impl(uv_loop_t* loop, ipc_frame.header.flags & UV_IPC_TCP_SERVER ? sizeof(ipc_frame) : sizeof(ipc_frame.header), NULL, - &ipc_header_req->overlapped); + &ipc_header_req->u.io.overlapped); if (!result && GetLastError() != ERROR_IO_PENDING) { err = GetLastError(); - CloseHandle(ipc_header_req->overlapped.hEvent); + CloseHandle(ipc_header_req->u.io.overlapped.hEvent); return err; } if (!result) { /* Request not completed immediately. Wait for it.*/ - if (WaitForSingleObject(ipc_header_req->overlapped.hEvent, INFINITE) != + if (WaitForSingleObject(ipc_header_req->u.io.overlapped.hEvent, INFINITE) != WAIT_OBJECT_0) { err = GetLastError(); - CloseHandle(ipc_header_req->overlapped.hEvent); + CloseHandle(ipc_header_req->u.io.overlapped.hEvent); return err; } } - ipc_header_req->queued_bytes = 0; - CloseHandle(ipc_header_req->overlapped.hEvent); - ipc_header_req->overlapped.hEvent = NULL; + ipc_header_req->u.io.queued_bytes = 0; + CloseHandle(ipc_header_req->u.io.overlapped.hEvent); + ipc_header_req->u.io.overlapped.hEvent = NULL; REGISTER_HANDLE_REQ(loop, handle, ipc_header_req); handle->reqs_pending++; - handle->write_reqs_pending++; + handle->stream.conn.write_reqs_pending++; /* If we don't have any raw data to write - we're done. */ if (!(ipc_frame.header.flags & UV_IPC_RAW_DATA)) { @@ -1331,28 +1335,28 @@ static int uv_pipe_write_impl(uv_loop_t* loop, return err; } else { /* Request completed immediately. */ - req->queued_bytes = 0; + req->u.io.queued_bytes = 0; } REGISTER_HANDLE_REQ(loop, handle, req); handle->reqs_pending++; - handle->write_reqs_pending++; + handle->stream.conn.write_reqs_pending++; POST_COMPLETION_FOR_REQ(loop, req); return 0; } else if (handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE) { req->write_buffer = bufs[0]; uv_insert_non_overlapped_write_req(handle, req); - if (handle->write_reqs_pending == 0) { + if (handle->stream.conn.write_reqs_pending == 0) { uv_queue_non_overlapped_write(handle); } /* Request queued by the kernel. */ - req->queued_bytes = uv__count_bufs(bufs, nbufs); - handle->write_queue_size += req->queued_bytes; + req->u.io.queued_bytes = bufs[0].len; + handle->write_queue_size += req->u.io.queued_bytes; } else if (handle->flags & UV_HANDLE_BLOCKING_WRITES) { /* Using overlapped IO, but wait for completion before returning */ - req->overlapped.hEvent = CreateEvent(NULL, 1, 0, NULL); - if (!req->overlapped.hEvent) { + req->u.io.overlapped.hEvent = CreateEvent(NULL, 1, 0, NULL); + if (!req->u.io.overlapped.hEvent) { uv_fatal_error(GetLastError(), "CreateEvent"); } @@ -1360,40 +1364,40 @@ static int uv_pipe_write_impl(uv_loop_t* loop, bufs[0].base, bufs[0].len, NULL, - &req->overlapped); + &req->u.io.overlapped); if (!result && GetLastError() != ERROR_IO_PENDING) { err = GetLastError(); - CloseHandle(req->overlapped.hEvent); + CloseHandle(req->u.io.overlapped.hEvent); return err; } if (result) { /* Request completed immediately. */ - req->queued_bytes = 0; + req->u.io.queued_bytes = 0; } else { - assert(ipc_header_req != NULL); /* Request queued by the kernel. */ - if (WaitForSingleObject(ipc_header_req->overlapped.hEvent, INFINITE) != + req->u.io.queued_bytes = bufs[0].len; + handle->write_queue_size += req->u.io.queued_bytes; + if (WaitForSingleObject(req->u.io.overlapped.hEvent, INFINITE) != WAIT_OBJECT_0) { err = GetLastError(); - CloseHandle(ipc_header_req->overlapped.hEvent); + CloseHandle(req->u.io.overlapped.hEvent); return uv_translate_sys_error(err); } } - CloseHandle(req->overlapped.hEvent); + CloseHandle(req->u.io.overlapped.hEvent); REGISTER_HANDLE_REQ(loop, handle, req); handle->reqs_pending++; - handle->write_reqs_pending++; - POST_COMPLETION_FOR_REQ(loop, req); + handle->stream.conn.write_reqs_pending++; return 0; } else { result = WriteFile(handle->handle, bufs[0].base, bufs[0].len, NULL, - &req->overlapped); + &req->u.io.overlapped); if (!result && GetLastError() != ERROR_IO_PENDING) { return GetLastError(); @@ -1401,11 +1405,11 @@ static int uv_pipe_write_impl(uv_loop_t* loop, if (result) { /* Request completed immediately. */ - req->queued_bytes = 0; + req->u.io.queued_bytes = 0; } else { /* Request queued by the kernel. */ - req->queued_bytes = uv__count_bufs(bufs, nbufs); - handle->write_queue_size += req->queued_bytes; + req->u.io.queued_bytes = bufs[0].len; + handle->write_queue_size += req->u.io.queued_bytes; } if (handle->flags & UV_HANDLE_EMULATE_IOCP) { @@ -1414,7 +1418,7 @@ static int uv_pipe_write_impl(uv_loop_t* loop, uv_fatal_error(GetLastError(), "CreateEvent"); } if (!RegisterWaitForSingleObject(&req->wait_handle, - req->overlapped.hEvent, post_completion_write_wait, (void*) req, + req->u.io.overlapped.hEvent, post_completion_write_wait, (void*) req, INFINITE, WT_EXECUTEINWAITTHREAD)) { return GetLastError(); } @@ -1423,7 +1427,7 @@ static int uv_pipe_write_impl(uv_loop_t* loop, REGISTER_HANDLE_REQ(loop, handle, req); handle->reqs_pending++; - handle->write_reqs_pending++; + handle->stream.conn.write_reqs_pending++; return 0; } @@ -1500,8 +1504,8 @@ void uv__pipe_insert_pending_socket(uv_pipe_t* handle, memcpy(&item->socket_info_ex, info, sizeof(item->socket_info_ex)); item->tcp_connection = tcp_connection; - QUEUE_INSERT_TAIL(&handle->pending_ipc_info.queue, &item->member); - handle->pending_ipc_info.queue_len++; + QUEUE_INSERT_TAIL(&handle->pipe.conn.pending_ipc_info.queue, &item->member); + handle->pipe.conn.pending_ipc_info.queue_len++; } @@ -1544,7 +1548,7 @@ void uv_process_pipe_read_req(uv_loop_t* loop, uv_pipe_t* handle, if (handle->ipc) { /* Use the IPC framing protocol to read the incoming data. */ - if (handle->remaining_ipc_rawdata_bytes == 0) { + if (handle->pipe.conn.remaining_ipc_rawdata_bytes == 0) { /* We're reading a new frame. First, read the header. */ assert(avail >= sizeof(ipc_frame.header)); @@ -1587,12 +1591,12 @@ void uv_process_pipe_read_req(uv_loop_t* loop, uv_pipe_t* handle, } if (ipc_frame.header.flags & UV_IPC_RAW_DATA) { - handle->remaining_ipc_rawdata_bytes = + handle->pipe.conn.remaining_ipc_rawdata_bytes = ipc_frame.header.raw_data_length; continue; } } else { - avail = min(avail, (DWORD)handle->remaining_ipc_rawdata_bytes); + avail = min(avail, (DWORD)handle->pipe.conn.remaining_ipc_rawdata_bytes); } } @@ -1610,9 +1614,9 @@ void uv_process_pipe_read_req(uv_loop_t* loop, uv_pipe_t* handle, NULL)) { /* Successful read */ if (handle->ipc) { - assert(handle->remaining_ipc_rawdata_bytes >= bytes); - handle->remaining_ipc_rawdata_bytes = - handle->remaining_ipc_rawdata_bytes - bytes; + assert(handle->pipe.conn.remaining_ipc_rawdata_bytes >= bytes); + handle->pipe.conn.remaining_ipc_rawdata_bytes = + handle->pipe.conn.remaining_ipc_rawdata_bytes - bytes; } handle->read_cb((uv_stream_t*)handle, bytes, &buf); @@ -1643,8 +1647,8 @@ void uv_process_pipe_write_req(uv_loop_t* loop, uv_pipe_t* handle, assert(handle->type == UV_NAMED_PIPE); - assert(handle->write_queue_size >= req->queued_bytes); - handle->write_queue_size -= req->queued_bytes; + assert(handle->write_queue_size >= req->u.io.queued_bytes); + handle->write_queue_size -= req->u.io.queued_bytes; UNREGISTER_HANDLE_REQ(loop, handle, req); @@ -1660,7 +1664,7 @@ void uv_process_pipe_write_req(uv_loop_t* loop, uv_pipe_t* handle, } if (req->ipc_header) { - if (req == &handle->ipc_header_write_req) { + if (req == &handle->pipe.conn.ipc_header_write_req) { req->type = UV_UNKNOWN_REQ; } else { free(req); @@ -1672,16 +1676,16 @@ void uv_process_pipe_write_req(uv_loop_t* loop, uv_pipe_t* handle, } } - handle->write_reqs_pending--; + handle->stream.conn.write_reqs_pending--; if (handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE && - handle->non_overlapped_writes_tail) { - assert(handle->write_reqs_pending > 0); + handle->pipe.conn.non_overlapped_writes_tail) { + assert(handle->stream.conn.write_reqs_pending > 0); uv_queue_non_overlapped_write(handle); } - if (handle->shutdown_req != NULL && - handle->write_reqs_pending == 0) { + if (handle->stream.conn.shutdown_req != NULL && + handle->stream.conn.write_reqs_pending == 0) { uv_want_endgame(loop, (uv_handle_t*)handle); } @@ -1704,11 +1708,11 @@ void uv_process_pipe_accept_req(uv_loop_t* loop, uv_pipe_t* handle, if (REQ_SUCCESS(req)) { assert(req->pipeHandle != INVALID_HANDLE_VALUE); - req->next_pending = handle->pending_accepts; - handle->pending_accepts = req; + req->next_pending = handle->pipe.serv.pending_accepts; + handle->pipe.serv.pending_accepts = req; - if (handle->connection_cb) { - handle->connection_cb((uv_stream_t*)handle, 0); + if (handle->stream.serv.connection_cb) { + handle->stream.serv.connection_cb((uv_stream_t*)handle, 0); } } else { if (req->pipeHandle != INVALID_HANDLE_VALUE) { @@ -1781,23 +1785,23 @@ void uv_process_pipe_shutdown_req(uv_loop_t* loop, uv_pipe_t* handle, static void eof_timer_init(uv_pipe_t* pipe) { int r; - assert(pipe->eof_timer == NULL); + assert(pipe->pipe.conn.eof_timer == NULL); assert(pipe->flags & UV_HANDLE_CONNECTION); - pipe->eof_timer = (uv_timer_t*) malloc(sizeof *pipe->eof_timer); + pipe->pipe.conn.eof_timer = (uv_timer_t*) malloc(sizeof *pipe->pipe.conn.eof_timer); - r = uv_timer_init(pipe->loop, pipe->eof_timer); + r = uv_timer_init(pipe->loop, pipe->pipe.conn.eof_timer); assert(r == 0); /* timers can't fail */ - pipe->eof_timer->data = pipe; - uv_unref((uv_handle_t*) pipe->eof_timer); + pipe->pipe.conn.eof_timer->data = pipe; + uv_unref((uv_handle_t*) pipe->pipe.conn.eof_timer); } static void eof_timer_start(uv_pipe_t* pipe) { assert(pipe->flags & UV_HANDLE_CONNECTION); - if (pipe->eof_timer != NULL) { - uv_timer_start(pipe->eof_timer, eof_timer_cb, eof_timeout, 0); + if (pipe->pipe.conn.eof_timer != NULL) { + uv_timer_start(pipe->pipe.conn.eof_timer, eof_timer_cb, eof_timeout, 0); } } @@ -1805,8 +1809,8 @@ static void eof_timer_start(uv_pipe_t* pipe) { static void eof_timer_stop(uv_pipe_t* pipe) { assert(pipe->flags & UV_HANDLE_CONNECTION); - if (pipe->eof_timer != NULL) { - uv_timer_stop(pipe->eof_timer); + if (pipe->pipe.conn.eof_timer != NULL) { + uv_timer_stop(pipe->pipe.conn.eof_timer); } } @@ -1829,7 +1833,7 @@ static void eof_timer_cb(uv_timer_t* timer) { /* Therefore we check here if the read request has completed but will */ /* be processed later. */ if ((pipe->flags & UV_HANDLE_READ_PENDING) && - HasOverlappedIoCompleted(&pipe->read_req.overlapped)) { + HasOverlappedIoCompleted(&pipe->read_req.u.io.overlapped)) { return; } @@ -1850,9 +1854,9 @@ static void eof_timer_cb(uv_timer_t* timer) { static void eof_timer_destroy(uv_pipe_t* pipe) { assert(pipe->flags & UV_HANDLE_CONNECTION); - if (pipe->eof_timer) { - uv_close((uv_handle_t*) pipe->eof_timer, eof_timer_close_cb); - pipe->eof_timer = NULL; + if (pipe->pipe.conn.eof_timer) { + uv_close((uv_handle_t*) pipe->pipe.conn.eof_timer, eof_timer_close_cb); + pipe->pipe.conn.eof_timer = NULL; } } @@ -1903,8 +1907,8 @@ int uv_pipe_open(uv_pipe_t* pipe, uv_file file) { if (pipe->ipc) { assert(!(pipe->flags & UV_HANDLE_NON_OVERLAPPED_PIPE)); - pipe->ipc_pid = uv_parent_pid(); - assert(pipe->ipc_pid != -1); + pipe->pipe.conn.ipc_pid = uv_parent_pid(); + assert(pipe->pipe.conn.ipc_pid != -1); } return 0; } @@ -2027,7 +2031,7 @@ static int uv__pipe_getname(const uv_pipe_t* handle, char* buffer, size_t* size) int uv_pipe_pending_count(uv_pipe_t* handle) { if (!handle->ipc) return 0; - return handle->pending_ipc_info.queue_len; + return handle->pipe.conn.pending_ipc_info.queue_len; } @@ -2060,7 +2064,7 @@ int uv_pipe_getpeername(const uv_pipe_t* handle, char* buffer, size_t* size) { uv_handle_type uv_pipe_pending_type(uv_pipe_t* handle) { if (!handle->ipc) return UV_UNKNOWN_HANDLE; - if (handle->pending_ipc_info.queue_len == 0) + if (handle->pipe.conn.pending_ipc_info.queue_len == 0) return UV_UNKNOWN_HANDLE; else return UV_TCP; diff --git a/deps/uv/src/win/poll.c b/deps/uv/src/win/poll.c index 4d8e1f99f65cb5..ce861d6ffc41eb 100644 --- a/deps/uv/src/win/poll.c +++ b/deps/uv/src/win/poll.c @@ -112,12 +112,12 @@ static void uv__fast_poll_submit_poll_req(uv_loop_t* loop, uv_poll_t* handle) { afd_poll_info->Handles[0].Events |= AFD_POLL_SEND | AFD_POLL_CONNECT_FAIL; } - memset(&req->overlapped, 0, sizeof req->overlapped); + memset(&req->u.io.overlapped, 0, sizeof req->u.io.overlapped); result = uv_msafd_poll((SOCKET) handle->peer_socket, afd_poll_info, afd_poll_info, - &req->overlapped); + &req->u.io.overlapped); if (result != 0 && WSAGetLastError() != WSA_IO_PENDING) { /* Queue this req, reporting an error. */ SET_REQ_ERROR(req, WSAGetLastError()); @@ -380,7 +380,7 @@ static DWORD WINAPI uv__slow_poll_thread_proc(void* arg) { } SET_REQ_SUCCESS(req); - req->overlapped.InternalHigh = (DWORD) reported_events; + req->u.io.overlapped.InternalHigh = (DWORD) reported_events; POST_COMPLETION_FOR_REQ(handle->loop, req); return 0; @@ -442,7 +442,7 @@ static void uv__slow_poll_process_poll_req(uv_loop_t* loop, uv_poll_t* handle, } } else { /* Got some events. */ - int events = req->overlapped.InternalHigh & handle->events & ~mask_events; + int events = req->u.io.overlapped.InternalHigh & handle->events & ~mask_events; if (events != 0) { handle->poll_cb(handle, 0, events); } diff --git a/deps/uv/src/win/process.c b/deps/uv/src/win/process.c index 3a0106f82d63e3..887595f89cc9b6 100644 --- a/deps/uv/src/win/process.c +++ b/deps/uv/src/win/process.c @@ -707,7 +707,7 @@ int make_program_env(char* env_block[], WCHAR** dst_ptr) { } /* second pass: copy to UTF-16 environment block */ - dst_copy = _malloca(env_len * sizeof(WCHAR)); + dst_copy = malloc(env_len * sizeof(WCHAR)); if (!dst_copy) { return ERROR_OUTOFMEMORY; } @@ -725,7 +725,7 @@ int make_program_env(char* env_block[], WCHAR** dst_ptr) { (int) (env_len - (ptr - dst_copy))); if (len <= 0) { DWORD err = GetLastError(); - _freea(dst_copy); + free(dst_copy); return err; } *ptr_copy++ = ptr; @@ -767,7 +767,7 @@ int make_program_env(char* env_block[], WCHAR** dst_ptr) { /* final pass: copy, in sort order, and inserting required variables */ dst = malloc((1+env_len) * sizeof(WCHAR)); if (!dst) { - _freea(dst_copy); + free(dst_copy); return ERROR_OUTOFMEMORY; } @@ -812,7 +812,7 @@ int make_program_env(char* env_block[], WCHAR** dst_ptr) { assert(env_len == (ptr - dst)); *ptr = L'\0'; - _freea(dst_copy); + free(dst_copy); *dst_ptr = dst; return 0; } @@ -1124,7 +1124,7 @@ int uv_spawn(uv_loop_t* loop, if (fdopt->flags & UV_CREATE_PIPE && fdopt->data.stream->type == UV_NAMED_PIPE && ((uv_pipe_t*) fdopt->data.stream)->ipc) { - ((uv_pipe_t*) fdopt->data.stream)->ipc_pid = info.dwProcessId; + ((uv_pipe_t*) fdopt->data.stream)->pipe.conn.ipc_pid = info.dwProcessId; } } diff --git a/deps/uv/src/win/req-inl.h b/deps/uv/src/win/req-inl.h index 46c7d9b106a869..b5e502eef5521a 100644 --- a/deps/uv/src/win/req-inl.h +++ b/deps/uv/src/win/req-inl.h @@ -29,7 +29,7 @@ #define SET_REQ_STATUS(req, status) \ - (req)->overlapped.Internal = (ULONG_PTR) (status) + (req)->u.io.overlapped.Internal = (ULONG_PTR) (status) #define SET_REQ_ERROR(req, error) \ SET_REQ_STATUS((req), NTSTATUS_FROM_WIN32((error))) @@ -38,7 +38,7 @@ SET_REQ_STATUS((req), STATUS_SUCCESS) #define GET_REQ_STATUS(req) \ - ((NTSTATUS) (req)->overlapped.Internal) + ((NTSTATUS) (req)->u.io.overlapped.Internal) #define REQ_SUCCESS(req) \ (NT_SUCCESS(GET_REQ_STATUS((req)))) @@ -74,7 +74,7 @@ if (!PostQueuedCompletionStatus((loop)->iocp, \ 0, \ 0, \ - &((req)->overlapped))) { \ + &((req)->u.io.overlapped))) { \ uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus"); \ } @@ -86,13 +86,24 @@ INLINE static void uv_req_init(uv_loop_t* loop, uv_req_t* req) { INLINE static uv_req_t* uv_overlapped_to_req(OVERLAPPED* overlapped) { - return CONTAINING_RECORD(overlapped, uv_req_t, overlapped); + return CONTAINING_RECORD(overlapped, uv_req_t, u.io.overlapped); } INLINE static void uv_insert_pending_req(uv_loop_t* loop, uv_req_t* req) { req->next_req = NULL; if (loop->pending_reqs_tail) { +#ifdef _DEBUG + /* Ensure the request is not already in the queue, or the queue + * will get corrupted. + */ + uv_req_t* current = loop->pending_reqs_tail; + do { + assert(req != current); + current = current->next_req; + } while(current != loop->pending_reqs_tail); +#endif + req->next_req = loop->pending_reqs_tail->next_req; loop->pending_reqs_tail->next_req = req; loop->pending_reqs_tail = req; diff --git a/deps/uv/src/win/stream-inl.h b/deps/uv/src/win/stream-inl.h index 97a6b90b50560a..b7a3c11958c274 100644 --- a/deps/uv/src/win/stream-inl.h +++ b/deps/uv/src/win/stream-inl.h @@ -41,7 +41,7 @@ INLINE static void uv_stream_init(uv_loop_t* loop, INLINE static void uv_connection_init(uv_stream_t* handle) { handle->flags |= UV_HANDLE_CONNECTION; - handle->write_reqs_pending = 0; + handle->stream.conn.write_reqs_pending = 0; uv_req_init(handle->loop, (uv_req_t*) &(handle->read_req)); handle->read_req.event_handle = NULL; @@ -49,7 +49,7 @@ INLINE static void uv_connection_init(uv_stream_t* handle) { handle->read_req.type = UV_READ; handle->read_req.data = handle; - handle->shutdown_req = NULL; + handle->stream.conn.shutdown_req = NULL; } diff --git a/deps/uv/src/win/stream.c b/deps/uv/src/win/stream.c index 36d88d00bd9893..a2466e5e9db8ba 100644 --- a/deps/uv/src/win/stream.c +++ b/deps/uv/src/win/stream.c @@ -216,7 +216,7 @@ int uv_shutdown(uv_shutdown_t* req, uv_stream_t* handle, uv_shutdown_cb cb) { req->cb = cb; handle->flags &= ~UV_HANDLE_WRITABLE; - handle->shutdown_req = req; + handle->stream.conn.shutdown_req = req; handle->reqs_pending++; REGISTER_HANDLE_REQ(loop, handle, req); diff --git a/deps/uv/src/win/tcp.c b/deps/uv/src/win/tcp.c index c5ddbed08f75ae..8b0e18c7cf3256 100644 --- a/deps/uv/src/win/tcp.c +++ b/deps/uv/src/win/tcp.c @@ -149,13 +149,13 @@ static int uv_tcp_set_socket(uv_loop_t* loop, uv_tcp_t* handle, int uv_tcp_init(uv_loop_t* loop, uv_tcp_t* handle) { uv_stream_init(loop, (uv_stream_t*) handle, UV_TCP); - handle->accept_reqs = NULL; - handle->pending_accepts = NULL; + handle->tcp.serv.accept_reqs = NULL; + handle->tcp.serv.pending_accepts = NULL; handle->socket = INVALID_SOCKET; handle->reqs_pending = 0; - handle->func_acceptex = NULL; - handle->func_connectex = NULL; - handle->processed_accepts = 0; + handle->tcp.serv.func_acceptex = NULL; + handle->tcp.conn.func_connectex = NULL; + handle->tcp.serv.processed_accepts = 0; handle->delayed_error = 0; return 0; @@ -168,10 +168,10 @@ void uv_tcp_endgame(uv_loop_t* loop, uv_tcp_t* handle) { uv_tcp_accept_t* req; if (handle->flags & UV_HANDLE_CONNECTION && - handle->shutdown_req != NULL && - handle->write_reqs_pending == 0) { + handle->stream.conn.shutdown_req != NULL && + handle->stream.conn.write_reqs_pending == 0) { - UNREGISTER_HANDLE_REQ(loop, handle, handle->shutdown_req); + UNREGISTER_HANDLE_REQ(loop, handle, handle->stream.conn.shutdown_req); err = 0; if (handle->flags & UV__HANDLE_CLOSING) { @@ -180,12 +180,12 @@ void uv_tcp_endgame(uv_loop_t* loop, uv_tcp_t* handle) { err = WSAGetLastError(); } - if (handle->shutdown_req->cb) { - handle->shutdown_req->cb(handle->shutdown_req, + if (handle->stream.conn.shutdown_req->cb) { + handle->stream.conn.shutdown_req->cb(handle->stream.conn.shutdown_req, uv_translate_sys_error(err)); } - handle->shutdown_req = NULL; + handle->stream.conn.shutdown_req = NULL; DECREASE_PENDING_REQ_COUNT(handle); return; } @@ -200,10 +200,10 @@ void uv_tcp_endgame(uv_loop_t* loop, uv_tcp_t* handle) { handle->flags |= UV_HANDLE_TCP_SOCKET_CLOSED; } - if (!(handle->flags & UV_HANDLE_CONNECTION) && handle->accept_reqs) { + if (!(handle->flags & UV_HANDLE_CONNECTION) && handle->tcp.serv.accept_reqs) { if (handle->flags & UV_HANDLE_EMULATE_IOCP) { for (i = 0; i < uv_simultaneous_server_accepts; i++) { - req = &handle->accept_reqs[i]; + req = &handle->tcp.serv.accept_reqs[i]; if (req->wait_handle != INVALID_HANDLE_VALUE) { UnregisterWait(req->wait_handle); req->wait_handle = INVALID_HANDLE_VALUE; @@ -215,8 +215,8 @@ void uv_tcp_endgame(uv_loop_t* loop, uv_tcp_t* handle) { } } - free(handle->accept_reqs); - handle->accept_reqs = NULL; + free(handle->tcp.serv.accept_reqs); + handle->tcp.serv.accept_reqs = NULL; } if (handle->flags & UV_HANDLE_CONNECTION && @@ -327,9 +327,9 @@ static void CALLBACK post_completion(void* context, BOOLEAN timed_out) { assert(!timed_out); if (!PostQueuedCompletionStatus(handle->loop->iocp, - req->overlapped.InternalHigh, + req->u.io.overlapped.InternalHigh, 0, - &req->overlapped)) { + &req->u.io.overlapped)) { uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus"); } } @@ -346,9 +346,9 @@ static void CALLBACK post_write_completion(void* context, BOOLEAN timed_out) { assert(!timed_out); if (!PostQueuedCompletionStatus(handle->loop->iocp, - req->overlapped.InternalHigh, + req->u.io.overlapped.InternalHigh, 0, - &req->overlapped)) { + &req->u.io.overlapped)) { uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus"); } } @@ -390,19 +390,19 @@ static void uv_tcp_queue_accept(uv_tcp_t* handle, uv_tcp_accept_t* req) { } /* Prepare the overlapped structure. */ - memset(&(req->overlapped), 0, sizeof(req->overlapped)); + memset(&(req->u.io.overlapped), 0, sizeof(req->u.io.overlapped)); if (handle->flags & UV_HANDLE_EMULATE_IOCP) { - req->overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1); + req->u.io.overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1); } - success = handle->func_acceptex(handle->socket, - accept_socket, - (void*)req->accept_buffer, - 0, - sizeof(struct sockaddr_storage), - sizeof(struct sockaddr_storage), - &bytes, - &req->overlapped); + success = handle->tcp.serv.func_acceptex(handle->socket, + accept_socket, + (void*)req->accept_buffer, + 0, + sizeof(struct sockaddr_storage), + sizeof(struct sockaddr_storage), + &bytes, + &req->u.io.overlapped); if (UV_SUCCEEDED_WITHOUT_IOCP(success)) { /* Process the req without IOCP. */ @@ -432,7 +432,7 @@ static void uv_tcp_queue_accept(uv_tcp_t* handle, uv_tcp_accept_t* req) { closesocket(accept_socket); /* Destroy the event handle */ if (handle->flags & UV_HANDLE_EMULATE_IOCP) { - CloseHandle(req->overlapped.hEvent); + CloseHandle(req->u.io.overlapped.hEvent); req->event_handle = NULL; } } @@ -449,7 +449,7 @@ static void uv_tcp_queue_read(uv_loop_t* loop, uv_tcp_t* handle) { assert(!(handle->flags & UV_HANDLE_READ_PENDING)); req = &handle->read_req; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); /* * Preallocate a read buffer if the number of active streams is below @@ -457,13 +457,13 @@ static void uv_tcp_queue_read(uv_loop_t* loop, uv_tcp_t* handle) { */ if (loop->active_tcp_streams < uv_active_tcp_streams_threshold) { handle->flags &= ~UV_HANDLE_ZERO_READ; - handle->alloc_cb((uv_handle_t*) handle, 65536, &handle->read_buffer); - if (handle->read_buffer.len == 0) { - handle->read_cb((uv_stream_t*) handle, UV_ENOBUFS, &handle->read_buffer); + handle->alloc_cb((uv_handle_t*) handle, 65536, &handle->tcp.conn.read_buffer); + if (handle->tcp.conn.read_buffer.len == 0) { + handle->read_cb((uv_stream_t*) handle, UV_ENOBUFS, &handle->tcp.conn.read_buffer); return; } - assert(handle->read_buffer.base != NULL); - buf = handle->read_buffer; + assert(handle->tcp.conn.read_buffer.base != NULL); + buf = handle->tcp.conn.read_buffer; } else { handle->flags |= UV_HANDLE_ZERO_READ; buf.base = (char*) &uv_zero_; @@ -471,10 +471,10 @@ static void uv_tcp_queue_read(uv_loop_t* loop, uv_tcp_t* handle) { } /* Prepare the overlapped structure. */ - memset(&(req->overlapped), 0, sizeof(req->overlapped)); + memset(&(req->u.io.overlapped), 0, sizeof(req->u.io.overlapped)); if (handle->flags & UV_HANDLE_EMULATE_IOCP) { assert(req->event_handle); - req->overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1); + req->u.io.overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1); } flags = 0; @@ -483,13 +483,13 @@ static void uv_tcp_queue_read(uv_loop_t* loop, uv_tcp_t* handle) { 1, &bytes, &flags, - &req->overlapped, + &req->u.io.overlapped, NULL); if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) { /* Process the req without IOCP. */ handle->flags |= UV_HANDLE_READ_PENDING; - req->overlapped.InternalHigh = bytes; + req->u.io.overlapped.InternalHigh = bytes; handle->reqs_pending++; uv_insert_pending_req(loop, (uv_req_t*)req); } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) { @@ -522,7 +522,7 @@ int uv_tcp_listen(uv_tcp_t* handle, int backlog, uv_connection_cb cb) { assert(backlog > 0); if (handle->flags & UV_HANDLE_LISTENING) { - handle->connection_cb = cb; + handle->stream.serv.connection_cb = cb; } if (handle->flags & UV_HANDLE_READING) { @@ -544,8 +544,8 @@ int uv_tcp_listen(uv_tcp_t* handle, int backlog, uv_connection_cb cb) { return handle->delayed_error; } - if (!handle->func_acceptex) { - if (!uv_get_acceptex_function(handle->socket, &handle->func_acceptex)) { + if (!handle->tcp.serv.func_acceptex) { + if (!uv_get_acceptex_function(handle->socket, &handle->tcp.serv.func_acceptex)) { return WSAEAFNOSUPPORT; } } @@ -556,21 +556,21 @@ int uv_tcp_listen(uv_tcp_t* handle, int backlog, uv_connection_cb cb) { } handle->flags |= UV_HANDLE_LISTENING; - handle->connection_cb = cb; + handle->stream.serv.connection_cb = cb; INCREASE_ACTIVE_COUNT(loop, handle); simultaneous_accepts = handle->flags & UV_HANDLE_TCP_SINGLE_ACCEPT ? 1 : uv_simultaneous_server_accepts; - if(!handle->accept_reqs) { - handle->accept_reqs = (uv_tcp_accept_t*) + if(!handle->tcp.serv.accept_reqs) { + handle->tcp.serv.accept_reqs = (uv_tcp_accept_t*) malloc(uv_simultaneous_server_accepts * sizeof(uv_tcp_accept_t)); - if (!handle->accept_reqs) { + if (!handle->tcp.serv.accept_reqs) { uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); } for (i = 0; i < simultaneous_accepts; i++) { - req = &handle->accept_reqs[i]; + req = &handle->tcp.serv.accept_reqs[i]; uv_req_init(loop, (uv_req_t*)req); req->type = UV_ACCEPT; req->accept_socket = INVALID_SOCKET; @@ -593,7 +593,7 @@ int uv_tcp_listen(uv_tcp_t* handle, int backlog, uv_connection_cb cb) { /* doesn't know how how many requests were initialized, so it will */ /* try to clean up {uv_simultaneous_server_accepts} requests. */ for (i = simultaneous_accepts; i < uv_simultaneous_server_accepts; i++) { - req = &handle->accept_reqs[i]; + req = &handle->tcp.serv.accept_reqs[i]; uv_req_init(loop, (uv_req_t*) req); req->type = UV_ACCEPT; req->accept_socket = INVALID_SOCKET; @@ -612,7 +612,7 @@ int uv_tcp_accept(uv_tcp_t* server, uv_tcp_t* client) { int err = 0; int family; - uv_tcp_accept_t* req = server->pending_accepts; + uv_tcp_accept_t* req = server->tcp.serv.pending_accepts; if (!req) { /* No valid connections found, so we error out. */ @@ -643,7 +643,7 @@ int uv_tcp_accept(uv_tcp_t* server, uv_tcp_t* client) { } /* Prepare the req to pick up a new connection */ - server->pending_accepts = req->next_pending; + server->tcp.serv.pending_accepts = req->next_pending; req->next_pending = NULL; req->accept_socket = INVALID_SOCKET; @@ -655,15 +655,15 @@ int uv_tcp_accept(uv_tcp_t* server, uv_tcp_t* client) { /* We better be switching to a single pending accept. */ assert(server->flags & UV_HANDLE_TCP_SINGLE_ACCEPT); - server->processed_accepts++; + server->tcp.serv.processed_accepts++; - if (server->processed_accepts >= uv_simultaneous_server_accepts) { - server->processed_accepts = 0; + if (server->tcp.serv.processed_accepts >= uv_simultaneous_server_accepts) { + server->tcp.serv.processed_accepts = 0; /* * All previously queued accept requests are now processed. * We now switch to queueing just a single accept. */ - uv_tcp_queue_accept(server, &server->accept_reqs[0]); + uv_tcp_queue_accept(server, &server->tcp.serv.accept_reqs[0]); server->flags &= ~UV_HANDLE_TCP_ACCEPT_STATE_CHANGING; server->flags |= UV_HANDLE_TCP_SINGLE_ACCEPT; } @@ -732,8 +732,8 @@ static int uv_tcp_try_connect(uv_connect_t* req, return handle->delayed_error; } - if (!handle->func_connectex) { - if (!uv_get_connectex_function(handle->socket, &handle->func_connectex)) { + if (!handle->tcp.conn.func_connectex) { + if (!uv_get_connectex_function(handle->socket, &handle->tcp.conn.func_connectex)) { return WSAEAFNOSUPPORT; } } @@ -742,15 +742,15 @@ static int uv_tcp_try_connect(uv_connect_t* req, req->type = UV_CONNECT; req->handle = (uv_stream_t*) handle; req->cb = cb; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); - success = handle->func_connectex(handle->socket, - addr, - addrlen, - NULL, - 0, - &bytes, - &req->overlapped); + success = handle->tcp.conn.func_connectex(handle->socket, + addr, + addrlen, + NULL, + 0, + &bytes, + &req->u.io.overlapped); if (UV_SUCCEEDED_WITHOUT_IOCP(success)) { /* Process the req without IOCP. */ @@ -828,13 +828,13 @@ int uv_tcp_write(uv_loop_t* loop, req->cb = cb; /* Prepare the overlapped structure. */ - memset(&(req->overlapped), 0, sizeof(req->overlapped)); + memset(&(req->u.io.overlapped), 0, sizeof(req->u.io.overlapped)); if (handle->flags & UV_HANDLE_EMULATE_IOCP) { req->event_handle = CreateEvent(NULL, 0, 0, NULL); if (!req->event_handle) { uv_fatal_error(GetLastError(), "CreateEvent"); } - req->overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1); + req->u.io.overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1); req->wait_handle = INVALID_HANDLE_VALUE; } @@ -843,23 +843,23 @@ int uv_tcp_write(uv_loop_t* loop, nbufs, &bytes, 0, - &req->overlapped, + &req->u.io.overlapped, NULL); if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) { /* Request completed immediately. */ - req->queued_bytes = 0; + req->u.io.queued_bytes = 0; handle->reqs_pending++; - handle->write_reqs_pending++; + handle->stream.conn.write_reqs_pending++; REGISTER_HANDLE_REQ(loop, handle, req); uv_insert_pending_req(loop, (uv_req_t*) req); } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) { /* Request queued by the kernel. */ - req->queued_bytes = uv__count_bufs(bufs, nbufs); + req->u.io.queued_bytes = uv__count_bufs(bufs, nbufs); handle->reqs_pending++; - handle->write_reqs_pending++; + handle->stream.conn.write_reqs_pending++; REGISTER_HANDLE_REQ(loop, handle, req); - handle->write_queue_size += req->queued_bytes; + handle->write_queue_size += req->u.io.queued_bytes; if (handle->flags & UV_HANDLE_EMULATE_IOCP && !RegisterWaitForSingleObject(&req->wait_handle, req->event_handle, post_write_completion, (void*) req, @@ -868,8 +868,13 @@ int uv_tcp_write(uv_loop_t* loop, uv_insert_pending_req(loop, (uv_req_t*)req); } } else { - /* Send failed due to an error. */ - return WSAGetLastError(); + /* Send failed due to an error, report it later */ + req->u.io.queued_bytes = 0; + handle->reqs_pending++; + handle->stream.conn.write_reqs_pending++; + REGISTER_HANDLE_REQ(loop, handle, req); + SET_REQ_ERROR(req, WSAGetLastError()); + uv_insert_pending_req(loop, (uv_req_t*) req); } return 0; @@ -882,7 +887,7 @@ int uv__tcp_try_write(uv_tcp_t* handle, int result; DWORD bytes; - if (handle->write_reqs_pending > 0) + if (handle->stream.conn.write_reqs_pending > 0) return UV_EAGAIN; result = WSASend(handle->socket, @@ -916,7 +921,7 @@ void uv_process_tcp_read_req(uv_loop_t* loop, uv_tcp_t* handle, handle->flags &= ~UV_HANDLE_READING; DECREASE_ACTIVE_COUNT(loop, handle); buf = (handle->flags & UV_HANDLE_ZERO_READ) ? - uv_buf_init(NULL, 0) : handle->read_buffer; + uv_buf_init(NULL, 0) : handle->tcp.conn.read_buffer; err = GET_REQ_SOCK_ERROR(req); @@ -934,13 +939,13 @@ void uv_process_tcp_read_req(uv_loop_t* loop, uv_tcp_t* handle, } else { if (!(handle->flags & UV_HANDLE_ZERO_READ)) { /* The read was done with a non-zero buffer length. */ - if (req->overlapped.InternalHigh > 0) { + if (req->u.io.overlapped.InternalHigh > 0) { /* Successful read */ handle->read_cb((uv_stream_t*)handle, - req->overlapped.InternalHigh, - &handle->read_buffer); + req->u.io.overlapped.InternalHigh, + &handle->tcp.conn.read_buffer); /* Read again only if bytes == buf.len */ - if (req->overlapped.InternalHigh < handle->read_buffer.len) { + if (req->u.io.overlapped.InternalHigh < handle->tcp.conn.read_buffer.len) { goto done; } } else { @@ -953,7 +958,7 @@ void uv_process_tcp_read_req(uv_loop_t* loop, uv_tcp_t* handle, buf.base = 0; buf.len = 0; - handle->read_cb((uv_stream_t*)handle, UV_EOF, &handle->read_buffer); + handle->read_cb((uv_stream_t*)handle, UV_EOF, &handle->tcp.conn.read_buffer); goto done; } } @@ -1032,8 +1037,8 @@ void uv_process_tcp_write_req(uv_loop_t* loop, uv_tcp_t* handle, assert(handle->type == UV_TCP); - assert(handle->write_queue_size >= req->queued_bytes); - handle->write_queue_size -= req->queued_bytes; + assert(handle->write_queue_size >= req->u.io.queued_bytes); + handle->write_queue_size -= req->u.io.queued_bytes; UNREGISTER_HANDLE_REQ(loop, handle, req); @@ -1057,9 +1062,9 @@ void uv_process_tcp_write_req(uv_loop_t* loop, uv_tcp_t* handle, req->cb(req, err); } - handle->write_reqs_pending--; - if (handle->shutdown_req != NULL && - handle->write_reqs_pending == 0) { + handle->stream.conn.write_reqs_pending--; + if (handle->stream.conn.shutdown_req != NULL && + handle->stream.conn.write_reqs_pending == 0) { uv_want_endgame(loop, (uv_handle_t*)handle); } @@ -1082,10 +1087,10 @@ void uv_process_tcp_accept_req(uv_loop_t* loop, uv_tcp_t* handle, if (handle->flags & UV_HANDLE_LISTENING) { handle->flags &= ~UV_HANDLE_LISTENING; DECREASE_ACTIVE_COUNT(loop, handle); - if (handle->connection_cb) { + if (handle->stream.serv.connection_cb) { err = GET_REQ_SOCK_ERROR(req); - handle->connection_cb((uv_stream_t*)handle, - uv_translate_sys_error(err)); + handle->stream.serv.connection_cb((uv_stream_t*)handle, + uv_translate_sys_error(err)); } } } else if (REQ_SUCCESS(req) && @@ -1094,12 +1099,12 @@ void uv_process_tcp_accept_req(uv_loop_t* loop, uv_tcp_t* handle, SO_UPDATE_ACCEPT_CONTEXT, (char*)&handle->socket, sizeof(handle->socket)) == 0) { - req->next_pending = handle->pending_accepts; - handle->pending_accepts = req; + req->next_pending = handle->tcp.serv.pending_accepts; + handle->tcp.serv.pending_accepts = req; /* Accept and SO_UPDATE_ACCEPT_CONTEXT were successful. */ - if (handle->connection_cb) { - handle->connection_cb((uv_stream_t*)handle, 0); + if (handle->stream.serv.connection_cb) { + handle->stream.serv.connection_cb((uv_stream_t*)handle, 0); } } else { /* Error related to accepted socket is ignored because the server */ @@ -1357,7 +1362,7 @@ void uv_tcp_close(uv_loop_t* loop, uv_tcp_t* tcp) { } } else if ((tcp->flags & UV_HANDLE_SHARED_TCP_SOCKET) && - tcp->accept_reqs != NULL) { + tcp->tcp.serv.accept_reqs != NULL) { /* Under normal circumstances closesocket() will ensure that all pending */ /* accept reqs are canceled. However, when the socket is shared the */ /* presence of another reference to the socket in another process will */ @@ -1371,9 +1376,9 @@ void uv_tcp_close(uv_loop_t* loop, uv_tcp_t* tcp) { /* cause the connection to be aborted. */ unsigned int i; for (i = 0; i < uv_simultaneous_server_accepts; i++) { - uv_tcp_accept_t* req = &tcp->accept_reqs[i]; + uv_tcp_accept_t* req = &tcp->tcp.serv.accept_reqs[i]; if (req->accept_socket != INVALID_SOCKET && - !HasOverlappedIoCompleted(&req->overlapped)) { + !HasOverlappedIoCompleted(&req->u.io.overlapped)) { closesocket(req->accept_socket); req->accept_socket = INVALID_SOCKET; } diff --git a/deps/uv/src/win/tty.c b/deps/uv/src/win/tty.c index 603421045cac58..7b1e4ba0557fca 100644 --- a/deps/uv/src/win/tty.c +++ b/deps/uv/src/win/tty.c @@ -142,28 +142,28 @@ int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, uv_file fd, int readable) { if (readable) { /* Initialize TTY input specific fields. */ tty->flags |= UV_HANDLE_TTY_READABLE | UV_HANDLE_READABLE; - tty->read_line_handle = NULL; - tty->read_line_buffer = uv_null_buf_; - tty->read_raw_wait = NULL; + tty->tty.rd.read_line_handle = NULL; + tty->tty.rd.read_line_buffer = uv_null_buf_; + tty->tty.rd.read_raw_wait = NULL; /* Init keycode-to-vt100 mapper state. */ - tty->last_key_len = 0; - tty->last_key_offset = 0; - tty->last_utf16_high_surrogate = 0; - memset(&tty->last_input_record, 0, sizeof tty->last_input_record); + tty->tty.rd.last_key_len = 0; + tty->tty.rd.last_key_offset = 0; + tty->tty.rd.last_utf16_high_surrogate = 0; + memset(&tty->tty.rd.last_input_record, 0, sizeof tty->tty.rd.last_input_record); } else { /* TTY output specific fields. */ tty->flags |= UV_HANDLE_WRITABLE; /* Init utf8-to-utf16 conversion state. */ - tty->utf8_bytes_left = 0; - tty->utf8_codepoint = 0; + tty->tty.wr.utf8_bytes_left = 0; + tty->tty.wr.utf8_codepoint = 0; /* Initialize eol conversion state */ - tty->previous_eol = 0; + tty->tty.wr.previous_eol = 0; /* Init ANSI parser state. */ - tty->ansi_parser_state = ANSI_NORMAL; + tty->tty.wr.ansi_parser_state = ANSI_NORMAL; } return 0; @@ -268,8 +268,8 @@ static void CALLBACK uv_tty_post_raw_read(void* data, BOOLEAN didTimeout) { handle = (uv_tty_t*) req->data; loop = handle->loop; - UnregisterWait(handle->read_raw_wait); - handle->read_raw_wait = NULL; + UnregisterWait(handle->tty.rd.read_raw_wait); + handle->tty.rd.read_raw_wait = NULL; SET_REQ_SUCCESS(req); POST_COMPLETION_FOR_REQ(loop, req); @@ -285,19 +285,19 @@ static void uv_tty_queue_read_raw(uv_loop_t* loop, uv_tty_t* handle) { assert(handle->handle && handle->handle != INVALID_HANDLE_VALUE); - handle->read_line_buffer = uv_null_buf_; + handle->tty.rd.read_line_buffer = uv_null_buf_; req = &handle->read_req; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); - r = RegisterWaitForSingleObject(&handle->read_raw_wait, + r = RegisterWaitForSingleObject(&handle->tty.rd.read_raw_wait, handle->handle, uv_tty_post_raw_read, (void*) req, INFINITE, WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE); if (!r) { - handle->read_raw_wait = NULL; + handle->tty.rd.read_raw_wait = NULL; SET_REQ_ERROR(req, GetLastError()); uv_insert_pending_req(loop, (uv_req_t*)req); } @@ -321,12 +321,12 @@ static DWORD CALLBACK uv_tty_line_read_thread(void* data) { handle = (uv_tty_t*) req->data; loop = handle->loop; - assert(handle->read_line_buffer.base != NULL); - assert(handle->read_line_buffer.len > 0); + assert(handle->tty.rd.read_line_buffer.base != NULL); + assert(handle->tty.rd.read_line_buffer.len > 0); /* ReadConsole can't handle big buffers. */ - if (handle->read_line_buffer.len < MAX_INPUT_BUFFER_LENGTH) { - bytes = handle->read_line_buffer.len; + if (handle->tty.rd.read_line_buffer.len < MAX_INPUT_BUFFER_LENGTH) { + bytes = handle->tty.rd.read_line_buffer.len; } else { bytes = MAX_INPUT_BUFFER_LENGTH; } @@ -335,7 +335,7 @@ static DWORD CALLBACK uv_tty_line_read_thread(void* data) { /* One utf-16 codeunit never takes more than 3 utf-8 codeunits to encode */ chars = bytes / 3; - if (ReadConsoleW(handle->read_line_handle, + if (ReadConsoleW(handle->tty.rd.read_line_handle, (void*) utf16, chars, &read_chars, @@ -344,12 +344,12 @@ static DWORD CALLBACK uv_tty_line_read_thread(void* data) { 0, utf16, read_chars, - handle->read_line_buffer.base, + handle->tty.rd.read_line_buffer.base, bytes, NULL, NULL); SET_REQ_SUCCESS(req); - req->overlapped.InternalHigh = read_bytes; + req->u.io.overlapped.InternalHigh = read_bytes; } else { SET_REQ_ERROR(req, GetLastError()); } @@ -368,30 +368,30 @@ static void uv_tty_queue_read_line(uv_loop_t* loop, uv_tty_t* handle) { assert(handle->handle && handle->handle != INVALID_HANDLE_VALUE); req = &handle->read_req; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); - handle->alloc_cb((uv_handle_t*) handle, 8192, &handle->read_line_buffer); - if (handle->read_line_buffer.len == 0) { + handle->alloc_cb((uv_handle_t*) handle, 8192, &handle->tty.rd.read_line_buffer); + if (handle->tty.rd.read_line_buffer.len == 0) { handle->read_cb((uv_stream_t*) handle, UV_ENOBUFS, - &handle->read_line_buffer); + &handle->tty.rd.read_line_buffer); return; } - assert(handle->read_line_buffer.base != NULL); + assert(handle->tty.rd.read_line_buffer.base != NULL); /* Duplicate the console handle, so if we want to cancel the read, we can */ /* just close this handle duplicate. */ - if (handle->read_line_handle == NULL) { + if (handle->tty.rd.read_line_handle == NULL) { HANDLE this_process = GetCurrentProcess(); r = DuplicateHandle(this_process, handle->handle, this_process, - &handle->read_line_handle, + &handle->tty.rd.read_line_handle, 0, 0, DUPLICATE_SAME_ACCESS); if (!r) { - handle->read_line_handle = NULL; + handle->tty.rd.read_line_handle = NULL; SET_REQ_ERROR(req, GetLastError()); uv_insert_pending_req(loop, (uv_req_t*)req); goto out; @@ -489,8 +489,8 @@ static const char* get_vt100_fn_key(DWORD code, char shift, char ctrl, void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, uv_req_t* req) { - /* Shortcut for handle->last_input_record.Event.KeyEvent. */ -#define KEV handle->last_input_record.Event.KeyEvent + /* Shortcut for handle->tty.rd.last_input_record.Event.KeyEvent. */ +#define KEV handle->tty.rd.last_input_record.Event.KeyEvent DWORD records_left, records_read; uv_buf_t buf; @@ -531,12 +531,12 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, buf = uv_null_buf_; buf_used = 0; - while ((records_left > 0 || handle->last_key_len > 0) && + while ((records_left > 0 || handle->tty.rd.last_key_len > 0) && (handle->flags & UV_HANDLE_READING)) { - if (handle->last_key_len == 0) { + if (handle->tty.rd.last_key_len == 0) { /* Read the next input record */ if (!ReadConsoleInputW(handle->handle, - &handle->last_input_record, + &handle->tty.rd.last_input_record, 1, &records_read)) { handle->flags &= ~UV_HANDLE_READING; @@ -551,7 +551,7 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, /* If the window was resized, recompute the virtual window size. This */ /* will trigger a SIGWINCH signal if the window size changed in an */ /* way that matters to libuv. */ - if (handle->last_input_record.EventType == WINDOW_BUFFER_SIZE_EVENT) { + if (handle->tty.rd.last_input_record.EventType == WINDOW_BUFFER_SIZE_EVENT) { CONSOLE_SCREEN_BUFFER_INFO info; EnterCriticalSection(&uv_tty_output_lock); @@ -567,7 +567,7 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, } /* Ignore other events that are not key or resize events. */ - if (handle->last_input_record.EventType != KEY_EVENT) { + if (handle->tty.rd.last_input_record.EventType != KEY_EVENT) { continue; } @@ -613,7 +613,7 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, if (KEV.uChar.UnicodeChar >= 0xD800 && KEV.uChar.UnicodeChar < 0xDC00) { /* UTF-16 high surrogate */ - handle->last_utf16_high_surrogate = KEV.uChar.UnicodeChar; + handle->tty.rd.last_utf16_high_surrogate = KEV.uChar.UnicodeChar; continue; } @@ -622,7 +622,7 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, if ((KEV.dwControlKeyState & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) && !(KEV.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) && KEV.bKeyDown) { - handle->last_key[0] = '\033'; + handle->tty.rd.last_key[0] = '\033'; prefix_len = 1; } else { prefix_len = 0; @@ -631,14 +631,14 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, if (KEV.uChar.UnicodeChar >= 0xDC00 && KEV.uChar.UnicodeChar < 0xE000) { /* UTF-16 surrogate pair */ - WCHAR utf16_buffer[2] = { handle->last_utf16_high_surrogate, + WCHAR utf16_buffer[2] = { handle->tty.rd.last_utf16_high_surrogate, KEV.uChar.UnicodeChar}; char_len = WideCharToMultiByte(CP_UTF8, 0, utf16_buffer, 2, - &handle->last_key[prefix_len], - sizeof handle->last_key, + &handle->tty.rd.last_key[prefix_len], + sizeof handle->tty.rd.last_key, NULL, NULL); } else { @@ -647,14 +647,14 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, 0, &KEV.uChar.UnicodeChar, 1, - &handle->last_key[prefix_len], - sizeof handle->last_key, + &handle->tty.rd.last_key[prefix_len], + sizeof handle->tty.rd.last_key, NULL, NULL); } /* Whatever happened, the last character wasn't a high surrogate. */ - handle->last_utf16_high_surrogate = 0; + handle->tty.rd.last_utf16_high_surrogate = 0; /* If the utf16 character(s) couldn't be converted something must */ /* be wrong. */ @@ -667,8 +667,8 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, goto out; } - handle->last_key_len = (unsigned char) (prefix_len + char_len); - handle->last_key_offset = 0; + handle->tty.rd.last_key_len = (unsigned char) (prefix_len + char_len); + handle->tty.rd.last_key_offset = 0; continue; } else { @@ -690,23 +690,23 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, /* Prefix with \x033 when the alt key was held. */ if (KEV.dwControlKeyState & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) { - handle->last_key[0] = '\033'; + handle->tty.rd.last_key[0] = '\033'; prefix_len = 1; } else { prefix_len = 0; } /* Copy the vt100 sequence to the handle buffer. */ - assert(prefix_len + vt100_len < sizeof handle->last_key); - memcpy(&handle->last_key[prefix_len], vt100, vt100_len); + assert(prefix_len + vt100_len < sizeof handle->tty.rd.last_key); + memcpy(&handle->tty.rd.last_key[prefix_len], vt100, vt100_len); - handle->last_key_len = (unsigned char) (prefix_len + vt100_len); - handle->last_key_offset = 0; + handle->tty.rd.last_key_len = (unsigned char) (prefix_len + vt100_len); + handle->tty.rd.last_key_offset = 0; continue; } } else { /* Copy any bytes left from the last keypress to the user buffer. */ - if (handle->last_key_offset < handle->last_key_len) { + if (handle->tty.rd.last_key_offset < handle->tty.rd.last_key_len) { /* Allocate a buffer if needed */ if (buf_used == 0) { handle->alloc_cb((uv_handle_t*) handle, 1024, &buf); @@ -717,7 +717,7 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, assert(buf.base != NULL); } - buf.base[buf_used++] = handle->last_key[handle->last_key_offset++]; + buf.base[buf_used++] = handle->tty.rd.last_key[handle->tty.rd.last_key_offset++]; /* If the buffer is full, emit it */ if ((size_t) buf_used == buf.len) { @@ -731,11 +731,11 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, /* Apply dwRepeat from the last input record. */ if (--KEV.wRepeatCount > 0) { - handle->last_key_offset = 0; + handle->tty.rd.last_key_offset = 0; continue; } - handle->last_key_len = 0; + handle->tty.rd.last_key_len = 0; continue; } } @@ -766,15 +766,15 @@ void uv_process_tty_read_line_req(uv_loop_t* loop, uv_tty_t* handle, assert(handle->type == UV_TTY); assert(handle->flags & UV_HANDLE_TTY_READABLE); - buf = handle->read_line_buffer; + buf = handle->tty.rd.read_line_buffer; handle->flags &= ~UV_HANDLE_READ_PENDING; - handle->read_line_buffer = uv_null_buf_; + handle->tty.rd.read_line_buffer = uv_null_buf_; if (!REQ_SUCCESS(req)) { /* Read was not successful */ if ((handle->flags & UV_HANDLE_READING) && - handle->read_line_handle != NULL) { + handle->tty.rd.read_line_handle != NULL) { /* Real error */ handle->flags &= ~UV_HANDLE_READING; DECREASE_ACTIVE_COUNT(loop, handle); @@ -789,7 +789,7 @@ void uv_process_tty_read_line_req(uv_loop_t* loop, uv_tty_t* handle, } else { /* Read successful */ /* TODO: read unicode, convert to utf-8 */ - DWORD bytes = req->overlapped.InternalHigh; + DWORD bytes = req->u.io.overlapped.InternalHigh; handle->read_cb((uv_stream_t*) handle, bytes, &buf); } @@ -811,7 +811,7 @@ void uv_process_tty_read_req(uv_loop_t* loop, uv_tty_t* handle, /* If the read_line_buffer member is zero, it must have been an raw read. */ /* Otherwise it was a line-buffered read. */ /* FIXME: This is quite obscure. Use a flag or something. */ - if (handle->read_line_buffer.len == 0) { + if (handle->tty.rd.read_line_buffer.len == 0) { uv_process_tty_read_raw_req(loop, handle, req); } else { uv_process_tty_read_line_req(loop, handle, req); @@ -840,7 +840,7 @@ int uv_tty_read_start(uv_tty_t* handle, uv_alloc_cb alloc_cb, /* Maybe the user stopped reading half-way while processing key events. */ /* Short-circuit if this could be the case. */ - if (handle->last_key_len > 0) { + if (handle->tty.rd.last_key_len > 0) { SET_REQ_SUCCESS(&handle->read_req); uv_insert_pending_req(handle->loop, (uv_req_t*) &handle->read_req); return 0; @@ -869,10 +869,10 @@ int uv_tty_read_stop(uv_tty_t* handle) { } /* Cancel line-buffered read */ - if (handle->read_line_handle != NULL) { + if (handle->tty.rd.read_line_handle != NULL) { /* Closing this handle will cancel the ReadConsole operation */ - CloseHandle(handle->read_line_handle); - handle->read_line_handle = NULL; + CloseHandle(handle->tty.rd.read_line_handle); + handle->tty.rd.read_line_handle = NULL; } @@ -1149,8 +1149,8 @@ static int uv_tty_clear(uv_tty_t* handle, int dir, char entire_screen, } while (0) static int uv_tty_set_style(uv_tty_t* handle, DWORD* error) { - unsigned short argc = handle->ansi_csi_argc; - unsigned short* argv = handle->ansi_csi_argv; + unsigned short argc = handle->tty.wr.ansi_csi_argc; + unsigned short* argv = handle->tty.wr.ansi_csi_argv; int i; CONSOLE_SCREEN_BUFFER_INFO info; @@ -1319,12 +1319,12 @@ static int uv_tty_save_state(uv_tty_t* handle, unsigned char save_attributes, uv_tty_update_virtual_window(&info); - handle->saved_position.X = info.dwCursorPosition.X; - handle->saved_position.Y = info.dwCursorPosition.Y - uv_tty_virtual_offset; + handle->tty.wr.saved_position.X = info.dwCursorPosition.X; + handle->tty.wr.saved_position.Y = info.dwCursorPosition.Y - uv_tty_virtual_offset; handle->flags |= UV_HANDLE_TTY_SAVED_POSITION; if (save_attributes) { - handle->saved_attributes = info.wAttributes & + handle->tty.wr.saved_attributes = info.wAttributes & (FOREGROUND_INTENSITY | BACKGROUND_INTENSITY); handle->flags |= UV_HANDLE_TTY_SAVED_ATTRIBUTES; } @@ -1344,9 +1344,9 @@ static int uv_tty_restore_state(uv_tty_t* handle, if (handle->flags & UV_HANDLE_TTY_SAVED_POSITION) { if (uv_tty_move_caret(handle, - handle->saved_position.X, + handle->tty.wr.saved_position.X, 0, - handle->saved_position.Y, + handle->tty.wr.saved_position.Y, 0, error) != 0) { return -1; @@ -1362,7 +1362,7 @@ static int uv_tty_restore_state(uv_tty_t* handle, new_attributes = info.wAttributes; new_attributes &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY); - new_attributes |= handle->saved_attributes; + new_attributes |= handle->tty.wr.saved_attributes; if (!SetConsoleTextAttribute(handle->handle, new_attributes)) { *error = GetLastError(); @@ -1412,10 +1412,10 @@ static int uv_tty_write_bufs(uv_tty_t* handle, } while (0) /* Cache for fast access */ - unsigned char utf8_bytes_left = handle->utf8_bytes_left; - unsigned int utf8_codepoint = handle->utf8_codepoint; - unsigned char previous_eol = handle->previous_eol; - unsigned char ansi_parser_state = handle->ansi_parser_state; + unsigned char utf8_bytes_left = handle->tty.wr.utf8_bytes_left; + unsigned int utf8_codepoint = handle->tty.wr.utf8_codepoint; + unsigned char previous_eol = handle->tty.wr.previous_eol; + unsigned char ansi_parser_state = handle->tty.wr.ansi_parser_state; /* Store the error here. If we encounter an error, stop trying to do i/o */ /* but keep parsing the buffer so we leave the parser in a consistent */ @@ -1492,7 +1492,7 @@ static int uv_tty_write_bufs(uv_tty_t* handle, case 0233: ansi_parser_state = ANSI_CSI; - handle->ansi_csi_argc = 0; + handle->tty.wr.ansi_csi_argc = 0; continue; } @@ -1500,7 +1500,7 @@ static int uv_tty_write_bufs(uv_tty_t* handle, switch (utf8_codepoint) { case '[': ansi_parser_state = ANSI_CSI; - handle->ansi_csi_argc = 0; + handle->tty.wr.ansi_csi_argc = 0; continue; case '^': @@ -1557,20 +1557,20 @@ static int uv_tty_write_bufs(uv_tty_t* handle, /* We were not currently parsing a number */ /* Check for too many arguments */ - if (handle->ansi_csi_argc >= ARRAY_SIZE(handle->ansi_csi_argv)) { + if (handle->tty.wr.ansi_csi_argc >= ARRAY_SIZE(handle->tty.wr.ansi_csi_argv)) { ansi_parser_state |= ANSI_IGNORE; continue; } ansi_parser_state |= ANSI_IN_ARG; - handle->ansi_csi_argc++; - handle->ansi_csi_argv[handle->ansi_csi_argc - 1] = + handle->tty.wr.ansi_csi_argc++; + handle->tty.wr.ansi_csi_argv[handle->tty.wr.ansi_csi_argc - 1] = (unsigned short) utf8_codepoint - '0'; continue; } else { /* We were already parsing a number. Parse next digit. */ uint32_t value = 10 * - handle->ansi_csi_argv[handle->ansi_csi_argc - 1]; + handle->tty.wr.ansi_csi_argv[handle->tty.wr.ansi_csi_argc - 1]; /* Check for overflow. */ if (value > UINT16_MAX) { @@ -1578,7 +1578,7 @@ static int uv_tty_write_bufs(uv_tty_t* handle, continue; } - handle->ansi_csi_argv[handle->ansi_csi_argc - 1] = + handle->tty.wr.ansi_csi_argv[handle->tty.wr.ansi_csi_argc - 1] = (unsigned short) value + (utf8_codepoint - '0'); continue; } @@ -1593,25 +1593,25 @@ static int uv_tty_write_bufs(uv_tty_t* handle, /* If ANSI_IN_ARG is not set, add another argument and */ /* default it to 0. */ /* Check for too many arguments */ - if (handle->ansi_csi_argc >= ARRAY_SIZE(handle->ansi_csi_argv)) { + if (handle->tty.wr.ansi_csi_argc >= ARRAY_SIZE(handle->tty.wr.ansi_csi_argv)) { ansi_parser_state |= ANSI_IGNORE; continue; } - handle->ansi_csi_argc++; - handle->ansi_csi_argv[handle->ansi_csi_argc - 1] = 0; + handle->tty.wr.ansi_csi_argc++; + handle->tty.wr.ansi_csi_argv[handle->tty.wr.ansi_csi_argc - 1] = 0; continue; } } else if (utf8_codepoint == '?' && !(ansi_parser_state & ANSI_IN_ARG) && - handle->ansi_csi_argc == 0) { + handle->tty.wr.ansi_csi_argc == 0) { /* Ignores '?' if it is the first character after CSI[ */ /* This is an extension character from the VT100 codeset */ /* that is supported and used by most ANSI terminals today. */ continue; } else if (utf8_codepoint >= '@' && utf8_codepoint <= '~' && - (handle->ansi_csi_argc > 0 || utf8_codepoint != '[')) { + (handle->tty.wr.ansi_csi_argc > 0 || utf8_codepoint != '[')) { int x, y, d; /* Command byte */ @@ -1619,50 +1619,50 @@ static int uv_tty_write_bufs(uv_tty_t* handle, case 'A': /* cursor up */ FLUSH_TEXT(); - y = -(handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 1); + y = -(handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1); uv_tty_move_caret(handle, 0, 1, y, 1, error); break; case 'B': /* cursor down */ FLUSH_TEXT(); - y = handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 1; + y = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1; uv_tty_move_caret(handle, 0, 1, y, 1, error); break; case 'C': /* cursor forward */ FLUSH_TEXT(); - x = handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 1; + x = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1; uv_tty_move_caret(handle, x, 1, 0, 1, error); break; case 'D': /* cursor back */ FLUSH_TEXT(); - x = -(handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 1); + x = -(handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1); uv_tty_move_caret(handle, x, 1, 0, 1, error); break; case 'E': /* cursor next line */ FLUSH_TEXT(); - y = handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 1; + y = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1; uv_tty_move_caret(handle, 0, 0, y, 1, error); break; case 'F': /* cursor previous line */ FLUSH_TEXT(); - y = -(handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 1); + y = -(handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1); uv_tty_move_caret(handle, 0, 0, y, 1, error); break; case 'G': /* cursor horizontal move absolute */ FLUSH_TEXT(); - x = (handle->ansi_csi_argc >= 1 && handle->ansi_csi_argv[0]) - ? handle->ansi_csi_argv[0] - 1 : 0; + x = (handle->tty.wr.ansi_csi_argc >= 1 && handle->tty.wr.ansi_csi_argv[0]) + ? handle->tty.wr.ansi_csi_argv[0] - 1 : 0; uv_tty_move_caret(handle, x, 0, 0, 1, error); break; @@ -1670,17 +1670,17 @@ static int uv_tty_write_bufs(uv_tty_t* handle, case 'f': /* cursor move absolute */ FLUSH_TEXT(); - y = (handle->ansi_csi_argc >= 1 && handle->ansi_csi_argv[0]) - ? handle->ansi_csi_argv[0] - 1 : 0; - x = (handle->ansi_csi_argc >= 2 && handle->ansi_csi_argv[1]) - ? handle->ansi_csi_argv[1] - 1 : 0; + y = (handle->tty.wr.ansi_csi_argc >= 1 && handle->tty.wr.ansi_csi_argv[0]) + ? handle->tty.wr.ansi_csi_argv[0] - 1 : 0; + x = (handle->tty.wr.ansi_csi_argc >= 2 && handle->tty.wr.ansi_csi_argv[1]) + ? handle->tty.wr.ansi_csi_argv[1] - 1 : 0; uv_tty_move_caret(handle, x, 0, y, 0, error); break; case 'J': /* Erase screen */ FLUSH_TEXT(); - d = handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 0; + d = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 0; if (d >= 0 && d <= 2) { uv_tty_clear(handle, d, 1, error); } @@ -1689,7 +1689,7 @@ static int uv_tty_write_bufs(uv_tty_t* handle, case 'K': /* Erase line */ FLUSH_TEXT(); - d = handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 0; + d = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 0; if (d >= 0 && d <= 2) { uv_tty_clear(handle, d, 0, error); } @@ -1715,8 +1715,8 @@ static int uv_tty_write_bufs(uv_tty_t* handle, case 'l': /* Hide the cursor */ - if (handle->ansi_csi_argc == 1 && - handle->ansi_csi_argv[0] == 25) { + if (handle->tty.wr.ansi_csi_argc == 1 && + handle->tty.wr.ansi_csi_argv[0] == 25) { FLUSH_TEXT(); uv_tty_set_cursor_visibility(handle, 0, error); } @@ -1724,8 +1724,8 @@ static int uv_tty_write_bufs(uv_tty_t* handle, case 'h': /* Show the cursor */ - if (handle->ansi_csi_argc == 1 && - handle->ansi_csi_argv[0] == 25) { + if (handle->tty.wr.ansi_csi_argc == 1 && + handle->tty.wr.ansi_csi_argv[0] == 25) { FLUSH_TEXT(); uv_tty_set_cursor_visibility(handle, 1, error); } @@ -1830,10 +1830,10 @@ static int uv_tty_write_bufs(uv_tty_t* handle, FLUSH_TEXT(); /* Copy cached values back to struct. */ - handle->utf8_bytes_left = utf8_bytes_left; - handle->utf8_codepoint = utf8_codepoint; - handle->previous_eol = previous_eol; - handle->ansi_parser_state = ansi_parser_state; + handle->tty.wr.utf8_bytes_left = utf8_bytes_left; + handle->tty.wr.utf8_codepoint = utf8_codepoint; + handle->tty.wr.previous_eol = previous_eol; + handle->tty.wr.ansi_parser_state = ansi_parser_state; LeaveCriticalSection(&uv_tty_output_lock); @@ -1861,10 +1861,10 @@ int uv_tty_write(uv_loop_t* loop, req->cb = cb; handle->reqs_pending++; - handle->write_reqs_pending++; + handle->stream.conn.write_reqs_pending++; REGISTER_HANDLE_REQ(loop, handle, req); - req->queued_bytes = 0; + req->u.io.queued_bytes = 0; if (!uv_tty_write_bufs(handle, bufs, nbufs, &error)) { SET_REQ_SUCCESS(req); @@ -1883,7 +1883,7 @@ int uv__tty_try_write(uv_tty_t* handle, unsigned int nbufs) { DWORD error; - if (handle->write_reqs_pending > 0) + if (handle->stream.conn.write_reqs_pending > 0) return UV_EAGAIN; if (uv_tty_write_bufs(handle, bufs, nbufs, &error)) @@ -1897,7 +1897,7 @@ void uv_process_tty_write_req(uv_loop_t* loop, uv_tty_t* handle, uv_write_t* req) { int err; - handle->write_queue_size -= req->queued_bytes; + handle->write_queue_size -= req->u.io.queued_bytes; UNREGISTER_HANDLE_REQ(loop, handle, req); if (req->cb) { @@ -1905,9 +1905,9 @@ void uv_process_tty_write_req(uv_loop_t* loop, uv_tty_t* handle, req->cb(req, uv_translate_sys_error(err)); } - handle->write_reqs_pending--; - if (handle->shutdown_req != NULL && - handle->write_reqs_pending == 0) { + handle->stream.conn.write_reqs_pending--; + if (handle->stream.conn.shutdown_req != NULL && + handle->stream.conn.write_reqs_pending == 0) { uv_want_endgame(loop, (uv_handle_t*)handle); } @@ -1933,20 +1933,20 @@ void uv_tty_close(uv_tty_t* handle) { void uv_tty_endgame(uv_loop_t* loop, uv_tty_t* handle) { if (!(handle->flags & UV_HANDLE_TTY_READABLE) && - handle->shutdown_req != NULL && - handle->write_reqs_pending == 0) { - UNREGISTER_HANDLE_REQ(loop, handle, handle->shutdown_req); + handle->stream.conn.shutdown_req != NULL && + handle->stream.conn.write_reqs_pending == 0) { + UNREGISTER_HANDLE_REQ(loop, handle, handle->stream.conn.shutdown_req); /* TTY shutdown is really just a no-op */ - if (handle->shutdown_req->cb) { + if (handle->stream.conn.shutdown_req->cb) { if (handle->flags & UV__HANDLE_CLOSING) { - handle->shutdown_req->cb(handle->shutdown_req, UV_ECANCELED); + handle->stream.conn.shutdown_req->cb(handle->stream.conn.shutdown_req, UV_ECANCELED); } else { - handle->shutdown_req->cb(handle->shutdown_req, 0); + handle->stream.conn.shutdown_req->cb(handle->stream.conn.shutdown_req, 0); } } - handle->shutdown_req = NULL; + handle->stream.conn.shutdown_req = NULL; DECREASE_PENDING_REQ_COUNT(handle); return; @@ -1957,12 +1957,12 @@ void uv_tty_endgame(uv_loop_t* loop, uv_tty_t* handle) { /* The console handle duplicate used for line reading should be destroyed */ /* by uv_tty_read_stop. */ assert(!(handle->flags & UV_HANDLE_TTY_READABLE) || - handle->read_line_handle == NULL); + handle->tty.rd.read_line_handle == NULL); /* The wait handle used for raw reading should be unregistered when the */ /* wait callback runs. */ assert(!(handle->flags & UV_HANDLE_TTY_READABLE) || - handle->read_raw_wait == NULL); + handle->tty.rd.read_raw_wait == NULL); assert(!(handle->flags & UV_HANDLE_CLOSED)); uv__handle_close(handle); diff --git a/deps/uv/src/win/udp.c b/deps/uv/src/win/udp.c index 73b5bd5e467b40..197e5d828f2ad4 100644 --- a/deps/uv/src/win/udp.c +++ b/deps/uv/src/win/udp.c @@ -244,7 +244,7 @@ static void uv_udp_queue_recv(uv_loop_t* loop, uv_udp_t* handle) { assert(!(handle->flags & UV_HANDLE_READ_PENDING)); req = &handle->recv_req; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); /* * Preallocate a read buffer if the number of active streams is below @@ -272,13 +272,13 @@ static void uv_udp_queue_recv(uv_loop_t* loop, uv_udp_t* handle) { &flags, (struct sockaddr*) &handle->recv_from, &handle->recv_from_len, - &req->overlapped, + &req->u.io.overlapped, NULL); if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) { /* Process the req without IOCP. */ handle->flags |= UV_HANDLE_READ_PENDING; - req->overlapped.InternalHigh = bytes; + req->u.io.overlapped.InternalHigh = bytes; handle->reqs_pending++; uv_insert_pending_req(loop, req); } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) { @@ -304,13 +304,13 @@ static void uv_udp_queue_recv(uv_loop_t* loop, uv_udp_t* handle) { 1, &bytes, &flags, - &req->overlapped, + &req->u.io.overlapped, NULL); if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) { /* Process the req without IOCP. */ handle->flags |= UV_HANDLE_READ_PENDING; - req->overlapped.InternalHigh = bytes; + req->u.io.overlapped.InternalHigh = bytes; handle->reqs_pending++; uv_insert_pending_req(loop, req); } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) { @@ -384,7 +384,7 @@ static int uv__send(uv_udp_send_t* req, req->type = UV_UDP_SEND; req->handle = handle; req->cb = cb; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); result = WSASendTo(handle->socket, (WSABUF*)bufs, @@ -393,22 +393,22 @@ static int uv__send(uv_udp_send_t* req, 0, addr, addrlen, - &req->overlapped, + &req->u.io.overlapped, NULL); if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) { /* Request completed immediately. */ - req->queued_bytes = 0; + req->u.io.queued_bytes = 0; handle->reqs_pending++; - handle->send_queue_size += req->queued_bytes; + handle->send_queue_size += req->u.io.queued_bytes; handle->send_queue_count++; REGISTER_HANDLE_REQ(loop, handle, req); uv_insert_pending_req(loop, (uv_req_t*)req); } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) { /* Request queued by the kernel. */ - req->queued_bytes = uv__count_bufs(bufs, nbufs); + req->u.io.queued_bytes = uv__count_bufs(bufs, nbufs); handle->reqs_pending++; - handle->send_queue_size += req->queued_bytes; + handle->send_queue_size += req->u.io.queued_bytes; handle->send_queue_count++; REGISTER_HANDLE_REQ(loop, handle, req); } else { @@ -459,7 +459,7 @@ void uv_process_udp_recv_req(uv_loop_t* loop, uv_udp_t* handle, /* Successful read */ partial = !REQ_SUCCESS(req); handle->recv_cb(handle, - req->overlapped.InternalHigh, + req->u.io.overlapped.InternalHigh, &handle->recv_buffer, (const struct sockaddr*) &handle->recv_from, partial ? UV_UDP_PARTIAL : 0); @@ -536,9 +536,9 @@ void uv_process_udp_send_req(uv_loop_t* loop, uv_udp_t* handle, assert(handle->type == UV_UDP); - assert(handle->send_queue_size >= req->queued_bytes); + assert(handle->send_queue_size >= req->u.io.queued_bytes); assert(handle->send_queue_count >= 1); - handle->send_queue_size -= req->queued_bytes; + handle->send_queue_size -= req->u.io.queued_bytes; handle->send_queue_count--; UNREGISTER_HANDLE_REQ(loop, handle, req); diff --git a/deps/uv/src/win/util.c b/deps/uv/src/win/util.c index 43d843ff5c42b5..3697d5aa6aaf20 100644 --- a/deps/uv/src/win/util.c +++ b/deps/uv/src/win/util.c @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include @@ -535,14 +534,14 @@ int uv_uptime(double* uptime) { return uv_translate_sys_error(result); } - free(malloced_buffer); - buffer_size *= 2; /* Don't let the buffer grow infinitely. */ if (buffer_size > 1 << 20) { goto internalError; } + free(malloced_buffer); + buffer = malloced_buffer = (BYTE*) malloc(buffer_size); if (malloced_buffer == NULL) { *uptime = 0; diff --git a/deps/uv/test/benchmark-getaddrinfo.c b/deps/uv/test/benchmark-getaddrinfo.c index c7f99a2fcb8720..1dbc23ddba009d 100644 --- a/deps/uv/test/benchmark-getaddrinfo.c +++ b/deps/uv/test/benchmark-getaddrinfo.c @@ -83,8 +83,9 @@ BENCHMARK_IMPL(getaddrinfo) { ASSERT(calls_initiated == TOTAL_CALLS); ASSERT(calls_completed == TOTAL_CALLS); - LOGF("getaddrinfo: %.0f req/s\n", - (double) calls_completed / (double) (end_time - start_time) * 1000.0); + fprintf(stderr, "getaddrinfo: %.0f req/s\n", + (double) calls_completed / (double) (end_time - start_time) * 1000.0); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; diff --git a/deps/uv/test/benchmark-loop-count.c b/deps/uv/test/benchmark-loop-count.c index 5cb813238d4f75..970a94c2fecb5c 100644 --- a/deps/uv/test/benchmark-loop-count.c +++ b/deps/uv/test/benchmark-loop-count.c @@ -62,10 +62,11 @@ BENCHMARK_IMPL(loop_count) { ASSERT(ticks == NUM_TICKS); - LOGF("loop_count: %d ticks in %.2fs (%.0f/s)\n", - NUM_TICKS, - ns / 1e9, - NUM_TICKS / (ns / 1e9)); + fprintf(stderr, "loop_count: %d ticks in %.2fs (%.0f/s)\n", + NUM_TICKS, + ns / 1e9, + NUM_TICKS / (ns / 1e9)); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; @@ -83,7 +84,8 @@ BENCHMARK_IMPL(loop_count_timed) { uv_run(loop, UV_RUN_DEFAULT); - LOGF("loop_count: %lu ticks (%.0f ticks/s)\n", ticks, ticks / 5.0); + fprintf(stderr, "loop_count: %lu ticks (%.0f ticks/s)\n", ticks, ticks / 5.0); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; diff --git a/deps/uv/test/benchmark-million-timers.c b/deps/uv/test/benchmark-million-timers.c index 6027d6088aa789..60a308bef13d40 100644 --- a/deps/uv/test/benchmark-million-timers.c +++ b/deps/uv/test/benchmark-million-timers.c @@ -75,10 +75,11 @@ BENCHMARK_IMPL(million_timers) { ASSERT(close_cb_called == NUM_TIMERS); free(timers); - LOGF("%.2f seconds total\n", (after_all - before_all) / 1e9); - LOGF("%.2f seconds init\n", (before_run - before_all) / 1e9); - LOGF("%.2f seconds dispatch\n", (after_run - before_run) / 1e9); - LOGF("%.2f seconds cleanup\n", (after_all - after_run) / 1e9); + fprintf(stderr, "%.2f seconds total\n", (after_all - before_all) / 1e9); + fprintf(stderr, "%.2f seconds init\n", (before_run - before_all) / 1e9); + fprintf(stderr, "%.2f seconds dispatch\n", (after_run - before_run) / 1e9); + fprintf(stderr, "%.2f seconds cleanup\n", (after_all - after_run) / 1e9); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; diff --git a/deps/uv/test/benchmark-ping-pongs.c b/deps/uv/test/benchmark-ping-pongs.c index bb560d7d21fd6b..646a7df9447036 100644 --- a/deps/uv/test/benchmark-ping-pongs.c +++ b/deps/uv/test/benchmark-ping-pongs.c @@ -80,7 +80,8 @@ static void pinger_close_cb(uv_handle_t* handle) { pinger_t* pinger; pinger = (pinger_t*)handle->data; - LOGF("ping_pongs: %d roundtrips/s\n", (1000 * pinger->pongs) / TIME); + fprintf(stderr, "ping_pongs: %d roundtrips/s\n", (1000 * pinger->pongs) / TIME); + fflush(stderr); free(pinger); diff --git a/deps/uv/test/benchmark-pound.c b/deps/uv/test/benchmark-pound.c index 587928549eac8a..79f36345037cd4 100644 --- a/deps/uv/test/benchmark-pound.c +++ b/deps/uv/test/benchmark-pound.c @@ -299,11 +299,12 @@ static int pound_it(int concurrency, /* Number of fractional seconds it took to run the benchmark. */ secs = (double)(end_time - start_time) / NANOSEC; - LOGF("%s-conn-pound-%d: %.0f accepts/s (%d failed)\n", - type, - concurrency, - closed_streams / secs, - conns_failed); + fprintf(stderr, "%s-conn-pound-%d: %.0f accepts/s (%d failed)\n", + type, + concurrency, + closed_streams / secs, + conns_failed); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; diff --git a/deps/uv/test/benchmark-pump.c b/deps/uv/test/benchmark-pump.c index d58f46a384b899..88f2dc5c658e27 100644 --- a/deps/uv/test/benchmark-pump.c +++ b/deps/uv/test/benchmark-pump.c @@ -90,9 +90,10 @@ static void show_stats(uv_timer_t* handle) { int i; #if PRINT_STATS - LOGF("connections: %d, write: %.1f gbit/s\n", - write_sockets, - gbit(nsent, STATS_INTERVAL)); + fprintf(stderr, "connections: %d, write: %.1f gbit/s\n", + write_sockets, + gbit(nsent, STATS_INTERVAL)); + fflush(stderr); #endif /* Exit if the show is over */ @@ -101,10 +102,11 @@ static void show_stats(uv_timer_t* handle) { uv_update_time(loop); diff = uv_now(loop) - start_time; - LOGF("%s_pump%d_client: %.1f gbit/s\n", - type == TCP ? "tcp" : "pipe", - write_sockets, - gbit(nsent_total, diff)); + fprintf(stderr, "%s_pump%d_client: %.1f gbit/s\n", + type == TCP ? "tcp" : "pipe", + write_sockets, + gbit(nsent_total, diff)); + fflush(stderr); for (i = 0; i < write_sockets; i++) { if (type == TCP) @@ -128,10 +130,11 @@ static void read_show_stats(void) { uv_update_time(loop); diff = uv_now(loop) - start_time; - LOGF("%s_pump%d_server: %.1f gbit/s\n", - type == TCP ? "tcp" : "pipe", - max_read_sockets, - gbit(nrecv_total, diff)); + fprintf(stderr, "%s_pump%d_server: %.1f gbit/s\n", + type == TCP ? "tcp" : "pipe", + max_read_sockets, + gbit(nrecv_total, diff)); + fflush(stderr); } @@ -213,7 +216,10 @@ static void do_write(uv_stream_t* stream) { static void connect_cb(uv_connect_t* req, int status) { int i; - if (status) LOG(uv_strerror(status)); + if (status) { + fprintf(stderr, "%s", uv_strerror(status)); + fflush(stderr); + } ASSERT(status == 0); write_sockets++; diff --git a/deps/uv/test/benchmark-sizes.c b/deps/uv/test/benchmark-sizes.c index 8ccf10ee475fb1..9bf42f91537d58 100644 --- a/deps/uv/test/benchmark-sizes.c +++ b/deps/uv/test/benchmark-sizes.c @@ -24,22 +24,23 @@ BENCHMARK_IMPL(sizes) { - LOGF("uv_shutdown_t: %u bytes\n", (unsigned int) sizeof(uv_shutdown_t)); - LOGF("uv_write_t: %u bytes\n", (unsigned int) sizeof(uv_write_t)); - LOGF("uv_connect_t: %u bytes\n", (unsigned int) sizeof(uv_connect_t)); - LOGF("uv_udp_send_t: %u bytes\n", (unsigned int) sizeof(uv_udp_send_t)); - LOGF("uv_tcp_t: %u bytes\n", (unsigned int) sizeof(uv_tcp_t)); - LOGF("uv_pipe_t: %u bytes\n", (unsigned int) sizeof(uv_pipe_t)); - LOGF("uv_tty_t: %u bytes\n", (unsigned int) sizeof(uv_tty_t)); - LOGF("uv_prepare_t: %u bytes\n", (unsigned int) sizeof(uv_prepare_t)); - LOGF("uv_check_t: %u bytes\n", (unsigned int) sizeof(uv_check_t)); - LOGF("uv_idle_t: %u bytes\n", (unsigned int) sizeof(uv_idle_t)); - LOGF("uv_async_t: %u bytes\n", (unsigned int) sizeof(uv_async_t)); - LOGF("uv_timer_t: %u bytes\n", (unsigned int) sizeof(uv_timer_t)); - LOGF("uv_fs_poll_t: %u bytes\n", (unsigned int) sizeof(uv_fs_poll_t)); - LOGF("uv_fs_event_t: %u bytes\n", (unsigned int) sizeof(uv_fs_event_t)); - LOGF("uv_process_t: %u bytes\n", (unsigned int) sizeof(uv_process_t)); - LOGF("uv_poll_t: %u bytes\n", (unsigned int) sizeof(uv_poll_t)); - LOGF("uv_loop_t: %u bytes\n", (unsigned int) sizeof(uv_loop_t)); + fprintf(stderr, "uv_shutdown_t: %u bytes\n", (unsigned int) sizeof(uv_shutdown_t)); + fprintf(stderr, "uv_write_t: %u bytes\n", (unsigned int) sizeof(uv_write_t)); + fprintf(stderr, "uv_connect_t: %u bytes\n", (unsigned int) sizeof(uv_connect_t)); + fprintf(stderr, "uv_udp_send_t: %u bytes\n", (unsigned int) sizeof(uv_udp_send_t)); + fprintf(stderr, "uv_tcp_t: %u bytes\n", (unsigned int) sizeof(uv_tcp_t)); + fprintf(stderr, "uv_pipe_t: %u bytes\n", (unsigned int) sizeof(uv_pipe_t)); + fprintf(stderr, "uv_tty_t: %u bytes\n", (unsigned int) sizeof(uv_tty_t)); + fprintf(stderr, "uv_prepare_t: %u bytes\n", (unsigned int) sizeof(uv_prepare_t)); + fprintf(stderr, "uv_check_t: %u bytes\n", (unsigned int) sizeof(uv_check_t)); + fprintf(stderr, "uv_idle_t: %u bytes\n", (unsigned int) sizeof(uv_idle_t)); + fprintf(stderr, "uv_async_t: %u bytes\n", (unsigned int) sizeof(uv_async_t)); + fprintf(stderr, "uv_timer_t: %u bytes\n", (unsigned int) sizeof(uv_timer_t)); + fprintf(stderr, "uv_fs_poll_t: %u bytes\n", (unsigned int) sizeof(uv_fs_poll_t)); + fprintf(stderr, "uv_fs_event_t: %u bytes\n", (unsigned int) sizeof(uv_fs_event_t)); + fprintf(stderr, "uv_process_t: %u bytes\n", (unsigned int) sizeof(uv_process_t)); + fprintf(stderr, "uv_poll_t: %u bytes\n", (unsigned int) sizeof(uv_poll_t)); + fprintf(stderr, "uv_loop_t: %u bytes\n", (unsigned int) sizeof(uv_loop_t)); + fflush(stderr); return 0; } diff --git a/deps/uv/test/benchmark-spawn.c b/deps/uv/test/benchmark-spawn.c index 9cae41a83afd61..ed9ad608f3790e 100644 --- a/deps/uv/test/benchmark-spawn.c +++ b/deps/uv/test/benchmark-spawn.c @@ -155,8 +155,9 @@ BENCHMARK_IMPL(spawn) { uv_update_time(loop); end_time = uv_now(loop); - LOGF("spawn: %.0f spawns/s\n", - (double) N / (double) (end_time - start_time) * 1000.0); + fprintf(stderr, "spawn: %.0f spawns/s\n", + (double) N / (double) (end_time - start_time) * 1000.0); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; diff --git a/deps/uv/test/run-benchmarks.c b/deps/uv/test/run-benchmarks.c index 8d4f549799e8b3..6e42623d54cdec 100644 --- a/deps/uv/test/run-benchmarks.c +++ b/deps/uv/test/run-benchmarks.c @@ -41,7 +41,8 @@ int main(int argc, char **argv) { case 2: return maybe_run_test(argc, argv); case 3: return run_test_part(argv[1], argv[2]); default: - LOGF("Too many arguments.\n"); + fprintf(stderr, "Too many arguments.\n"); + fflush(stderr); return EXIT_FAILURE; } diff --git a/deps/uv/test/run-tests.c b/deps/uv/test/run-tests.c index e92c93008e72ef..1f458745327398 100644 --- a/deps/uv/test/run-tests.c +++ b/deps/uv/test/run-tests.c @@ -56,7 +56,8 @@ int main(int argc, char **argv) { case 2: return maybe_run_test(argc, argv); case 3: return run_test_part(argv[1], argv[2]); default: - LOGF("Too many arguments.\n"); + fprintf(stderr, "Too many arguments.\n"); + fflush(stderr); return EXIT_FAILURE; } diff --git a/deps/uv/test/runner.c b/deps/uv/test/runner.c index e896d43b7627df..e094defc7e7de5 100644 --- a/deps/uv/test/runner.c +++ b/deps/uv/test/runner.c @@ -43,13 +43,14 @@ static void log_progress(int total, total = 1; progress = 100 * (passed + failed + skipped + todos) / total; - LOGF("[%% %3d|+ %3d|- %3d|T %3d|S %3d]: %s", - progress, - passed, - failed, - todos, - skipped, - name); + fprintf(stderr, "[%% %3d|+ %3d|- %3d|T %3d|S %3d]: %s", + progress, + passed, + failed, + todos, + skipped, + name); + fflush(stderr); } @@ -109,7 +110,8 @@ int run_tests(int benchmark_output) { } if (tap_output) { - LOGF("1..%d\n", total); + fprintf(stderr, "1..%d\n", total); + fflush(stderr); } /* Run all tests. */ @@ -184,7 +186,8 @@ void log_tap_result(int test_count, reason[0] = '\0'; } - LOGF("%s %d - %s%s%s\n", result, test_count, test, directive, reason); + fprintf(stderr, "%s %d - %s%s%s\n", result, test_count, test, directive, reason); + fflush(stderr); } @@ -320,49 +323,55 @@ int run_test(const char* test, /* Show error and output from processes if the test failed. */ if (status != 0 || task->show_output) { if (tap_output) { - LOGF("#"); + fprintf(stderr, "#"); } else if (status == TEST_TODO) { - LOGF("\n`%s` todo\n", test); + fprintf(stderr, "\n`%s` todo\n", test); } else if (status == TEST_SKIP) { - LOGF("\n`%s` skipped\n", test); + fprintf(stderr, "\n`%s` skipped\n", test); } else if (status != 0) { - LOGF("\n`%s` failed: %s\n", test, errmsg); + fprintf(stderr, "\n`%s` failed: %s\n", test, errmsg); } else { - LOGF("\n"); + fprintf(stderr, "\n"); } + fflush(stderr); for (i = 0; i < process_count; i++) { switch (process_output_size(&processes[i])) { case -1: - LOGF("Output from process `%s`: (unavailable)\n", - process_get_name(&processes[i])); + fprintf(stderr, "Output from process `%s`: (unavailable)\n", + process_get_name(&processes[i])); + fflush(stderr); break; case 0: - LOGF("Output from process `%s`: (no output)\n", - process_get_name(&processes[i])); + fprintf(stderr, "Output from process `%s`: (no output)\n", + process_get_name(&processes[i])); + fflush(stderr); break; default: - LOGF("Output from process `%s`:\n", process_get_name(&processes[i])); + fprintf(stderr, "Output from process `%s`:\n", process_get_name(&processes[i])); + fflush(stderr); process_copy_output(&processes[i], fileno(stderr)); break; } } if (!tap_output) { - LOG("=============================================================\n"); + fprintf(stderr, "=============================================================\n"); } /* In benchmark mode show concise output from the main process. */ } else if (benchmark_output) { switch (process_output_size(main_proc)) { case -1: - LOGF("%s: (unavailable)\n", test); + fprintf(stderr, "%s: (unavailable)\n", test); + fflush(stderr); break; case 0: - LOGF("%s: (no output)\n", test); + fprintf(stderr, "%s: (no output)\n", test); + fflush(stderr); break; default: @@ -397,7 +406,8 @@ int run_test_part(const char* test, const char* part) { } } - LOGF("No test part with that name: %s:%s\n", test, part); + fprintf(stderr, "No test part with that name: %s:%s\n", test, part); + fflush(stderr); return 255; } diff --git a/deps/uv/test/task.h b/deps/uv/test/task.h index 07584c52996f8c..ea0503e8feefe4 100644 --- a/deps/uv/test/task.h +++ b/deps/uv/test/task.h @@ -76,19 +76,6 @@ typedef enum { PIPE } stream_type; -/* Log to stderr. */ -#define LOG(...) \ - do { \ - fprintf(stderr, "%s", __VA_ARGS__); \ - fflush(stderr); \ - } while (0) - -#define LOGF(...) \ - do { \ - fprintf(stderr, __VA_ARGS__); \ - fflush(stderr); \ - } while (0) - /* Die with fatal error. */ #define FATAL(msg) \ do { \ @@ -158,13 +145,15 @@ enum test_status { #define RETURN_TODO(explanation) \ do { \ - LOGF("%s\n", explanation); \ + fprintf(stderr, "%s\n", explanation); \ + fflush(stderr); \ return TEST_TODO; \ } while (0) #define RETURN_SKIP(explanation) \ do { \ - LOGF("%s\n", explanation); \ + fprintf(stderr, "%s\n", explanation); \ + fflush(stderr); \ return TEST_SKIP; \ } while (0) @@ -190,10 +179,15 @@ enum test_status { #include +/* Define inline for MSVC */ +# ifdef _MSC_VER +# define inline __inline +# endif + /* Emulate snprintf() on Windows, _snprintf() doesn't zero-terminate the buffer * on overflow... */ -static int snprintf(char* buf, size_t len, const char* fmt, ...) { +inline int snprintf(char* buf, size_t len, const char* fmt, ...) { va_list ap; int n; diff --git a/deps/uv/test/test-fs.c b/deps/uv/test/test-fs.c index cc5dc744501ec4..a0600b30797dd9 100644 --- a/deps/uv/test/test-fs.c +++ b/deps/uv/test/test-fs.c @@ -1094,7 +1094,8 @@ TEST_IMPL(fs_fstat) { #elif defined(__sun) || \ defined(_BSD_SOURCE) || \ defined(_SVID_SOURCE) || \ - defined(_XOPEN_SOURCE) + defined(_XOPEN_SOURCE) || \ + defined(_DEFAULT_SOURCE) ASSERT(s->st_atim.tv_sec == t.st_atim.tv_sec); ASSERT(s->st_atim.tv_nsec == t.st_atim.tv_nsec); ASSERT(s->st_mtim.tv_sec == t.st_mtim.tv_sec); @@ -1155,6 +1156,7 @@ TEST_IMPL(fs_access) { /* Setup. */ unlink("test_file"); + rmdir("test_dir"); loop = uv_default_loop(); @@ -1198,6 +1200,16 @@ TEST_IMPL(fs_access) { ASSERT(req.result == 0); uv_fs_req_cleanup(&req); + /* Directory access */ + r = uv_fs_mkdir(loop, &req, "test_dir", 0777, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&req); + + r = uv_fs_access(loop, &req, "test_dir", W_OK, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + /* * Run the loop just to check we don't have make any extraneous uv_ref() * calls. This should drop out immediately. @@ -1206,6 +1218,7 @@ TEST_IMPL(fs_access) { /* Cleanup. */ unlink("test_file"); + rmdir("test_dir"); MAKE_VALGRIND_HAPPY(); return 0; @@ -1310,6 +1323,65 @@ TEST_IMPL(fs_chmod) { } +TEST_IMPL(fs_unlink_readonly) { + int r; + uv_fs_t req; + uv_file file; + + /* Setup. */ + unlink("test_file"); + + loop = uv_default_loop(); + + r = uv_fs_open(loop, + &req, + "test_file", + O_RDWR | O_CREAT, + S_IWUSR | S_IRUSR, + NULL); + ASSERT(r >= 0); + ASSERT(req.result >= 0); + file = req.result; + uv_fs_req_cleanup(&req); + + iov = uv_buf_init(test_buf, sizeof(test_buf)); + r = uv_fs_write(loop, &req, file, &iov, 1, -1, NULL); + ASSERT(r == sizeof(test_buf)); + ASSERT(req.result == sizeof(test_buf)); + uv_fs_req_cleanup(&req); + + close(file); + + /* Make the file read-only */ + r = uv_fs_chmod(loop, &req, "test_file", 0400, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + check_permission("test_file", 0400); + + /* Try to unlink the file */ + r = uv_fs_unlink(loop, &req, "test_file", NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + /* + * Run the loop just to check we don't have make any extraneous uv_ref() + * calls. This should drop out immediately. + */ + uv_run(loop, UV_RUN_DEFAULT); + + /* Cleanup. */ + uv_fs_chmod(loop, &req, "test_file", 0600, NULL); + uv_fs_req_cleanup(&req); + unlink("test_file"); + + MAKE_VALGRIND_HAPPY(); + return 0; +} + + TEST_IMPL(fs_chown) { int r; uv_fs_t req; diff --git a/deps/uv/test/test-handle-fileno.c b/deps/uv/test/test-handle-fileno.c index df5e984ab74338..3fe933adebdd87 100644 --- a/deps/uv/test/test-handle-fileno.c +++ b/deps/uv/test/test-handle-fileno.c @@ -102,7 +102,8 @@ TEST_IMPL(handle_fileno) { tty_fd = get_tty_fd(); if (tty_fd < 0) { - LOGF("Cannot open a TTY fd"); + fprintf(stderr, "Cannot open a TTY fd"); + fflush(stderr); } else { r = uv_tty_init(loop, &tty, tty_fd, 0); ASSERT(r == 0); diff --git a/deps/uv/test/test-idle.c b/deps/uv/test/test-idle.c index 0e991c368cfd81..f49d1964827278 100644 --- a/deps/uv/test/test-idle.c +++ b/deps/uv/test/test-idle.c @@ -46,7 +46,8 @@ static void timer_cb(uv_timer_t* handle) { uv_close((uv_handle_t*) &timer_handle, close_cb); timer_cb_called++; - LOGF("timer_cb %d\n", timer_cb_called); + fprintf(stderr, "timer_cb %d\n", timer_cb_called); + fflush(stderr); } @@ -54,7 +55,8 @@ static void idle_cb(uv_idle_t* handle) { ASSERT(handle == &idle_handle); idle_cb_called++; - LOGF("idle_cb %d\n", idle_cb_called); + fprintf(stderr, "idle_cb %d\n", idle_cb_called); + fflush(stderr); } @@ -62,7 +64,8 @@ static void check_cb(uv_check_t* handle) { ASSERT(handle == &check_handle); check_cb_called++; - LOGF("check_cb %d\n", check_cb_called); + fprintf(stderr, "check_cb %d\n", check_cb_called); + fflush(stderr); } diff --git a/deps/uv/test/test-ip6-addr.c b/deps/uv/test/test-ip6-addr.c index cf8491fb1b4d15..869b099e0fccaf 100644 --- a/deps/uv/test/test-ip6-addr.c +++ b/deps/uv/test/test-ip6-addr.c @@ -77,14 +77,16 @@ TEST_IMPL(ip6_addr_link_local) { device_name); #endif - LOGF("Testing link-local address %s " - "(iface_index: 0x%02x, device_name: %s)\n", - scoped_addr, - iface_index, - device_name); + fprintf(stderr, "Testing link-local address %s " + "(iface_index: 0x%02x, device_name: %s)\n", + scoped_addr, + iface_index, + device_name); + fflush(stderr); ASSERT(0 == uv_ip6_addr(scoped_addr, TEST_PORT, &addr)); - LOGF("Got scope_id 0x%02x\n", addr.sin6_scope_id); + fprintf(stderr, "Got scope_id 0x%02x\n", addr.sin6_scope_id); + fflush(stderr); ASSERT(iface_index == addr.sin6_scope_id); } diff --git a/deps/uv/test/test-list.h b/deps/uv/test/test-list.h index aac15e0d9df0b7..1e3c13d5e9267d 100644 --- a/deps/uv/test/test-list.h +++ b/deps/uv/test/test-list.h @@ -43,6 +43,7 @@ TEST_DECLARE (semaphore_1) TEST_DECLARE (semaphore_2) TEST_DECLARE (semaphore_3) TEST_DECLARE (tty) +TEST_DECLARE (tty_file) TEST_DECLARE (stdio_over_pipes) TEST_DECLARE (ip6_pton) TEST_DECLARE (ipc_listen_before_write) @@ -61,6 +62,7 @@ TEST_DECLARE (multiple_listen) TEST_DECLARE (tcp_write_after_connect) #endif TEST_DECLARE (tcp_writealot) +TEST_DECLARE (tcp_write_fail) TEST_DECLARE (tcp_try_write) TEST_DECLARE (tcp_write_queue_order) TEST_DECLARE (tcp_open) @@ -195,6 +197,9 @@ TEST_DECLARE (fail_always) TEST_DECLARE (pass_always) TEST_DECLARE (socket_buffer_size) TEST_DECLARE (spawn_fails) +#ifndef _WIN32 +TEST_DECLARE (spawn_fails_check_for_waitpid_cleanup) +#endif TEST_DECLARE (spawn_exit_code) TEST_DECLARE (spawn_stdout) TEST_DECLARE (spawn_stdin) @@ -209,6 +214,8 @@ TEST_DECLARE (spawn_setuid_fails) TEST_DECLARE (spawn_setgid_fails) TEST_DECLARE (spawn_stdout_to_file) TEST_DECLARE (spawn_stdout_and_stderr_to_file) +TEST_DECLARE (spawn_stdout_and_stderr_to_file2) +TEST_DECLARE (spawn_stdout_and_stderr_to_file_swap) TEST_DECLARE (spawn_auto_unref) TEST_DECLARE (spawn_closed_process_io) TEST_DECLARE (spawn_reads_child_path) @@ -227,6 +234,7 @@ TEST_DECLARE (fs_mkdtemp) TEST_DECLARE (fs_fstat) TEST_DECLARE (fs_access) TEST_DECLARE (fs_chmod) +TEST_DECLARE (fs_unlink_readonly) TEST_DECLARE (fs_chown) TEST_DECLARE (fs_link) TEST_DECLARE (fs_readlink) @@ -343,6 +351,7 @@ TASK_LIST_START #endif TEST_ENTRY (pipe_set_non_blocking) TEST_ENTRY (tty) + TEST_ENTRY (tty_file) TEST_ENTRY (stdio_over_pipes) TEST_ENTRY (ip6_pton) TEST_ENTRY (ipc_listen_before_write) @@ -372,6 +381,9 @@ TASK_LIST_START TEST_ENTRY (tcp_writealot) TEST_HELPER (tcp_writealot, tcp4_echo_server) + TEST_ENTRY (tcp_write_fail) + TEST_HELPER (tcp_write_fail, tcp4_echo_server) + TEST_ENTRY (tcp_try_write) TEST_ENTRY (tcp_write_queue_order) @@ -551,6 +563,9 @@ TASK_LIST_START TEST_ENTRY (socket_buffer_size) TEST_ENTRY (spawn_fails) +#ifndef _WIN32 + TEST_ENTRY (spawn_fails_check_for_waitpid_cleanup) +#endif TEST_ENTRY (spawn_exit_code) TEST_ENTRY (spawn_stdout) TEST_ENTRY (spawn_stdin) @@ -565,6 +580,8 @@ TASK_LIST_START TEST_ENTRY (spawn_setgid_fails) TEST_ENTRY (spawn_stdout_to_file) TEST_ENTRY (spawn_stdout_and_stderr_to_file) + TEST_ENTRY (spawn_stdout_and_stderr_to_file2) + TEST_ENTRY (spawn_stdout_and_stderr_to_file_swap) TEST_ENTRY (spawn_auto_unref) TEST_ENTRY (spawn_closed_process_io) TEST_ENTRY (spawn_reads_child_path) @@ -611,6 +628,7 @@ TASK_LIST_START TEST_ENTRY (fs_fstat) TEST_ENTRY (fs_access) TEST_ENTRY (fs_chmod) + TEST_ENTRY (fs_unlink_readonly) TEST_ENTRY (fs_chown) TEST_ENTRY (fs_utime) TEST_ENTRY (fs_futime) diff --git a/deps/uv/test/test-loop-handles.c b/deps/uv/test/test-loop-handles.c index 0986de52981e1b..c3e8498ae90a6b 100644 --- a/deps/uv/test/test-loop-handles.c +++ b/deps/uv/test/test-loop-handles.c @@ -113,7 +113,8 @@ static void timer_cb(uv_timer_t* handle) { static void idle_2_close_cb(uv_handle_t* handle) { - LOG("IDLE_2_CLOSE_CB\n"); + fprintf(stderr, "%s", "IDLE_2_CLOSE_CB\n"); + fflush(stderr); ASSERT(handle == (uv_handle_t*)&idle_2_handle); @@ -125,7 +126,8 @@ static void idle_2_close_cb(uv_handle_t* handle) { static void idle_2_cb(uv_idle_t* handle) { - LOG("IDLE_2_CB\n"); + fprintf(stderr, "%s", "IDLE_2_CB\n"); + fflush(stderr); ASSERT(handle == &idle_2_handle); @@ -138,7 +140,8 @@ static void idle_2_cb(uv_idle_t* handle) { static void idle_1_cb(uv_idle_t* handle) { int r; - LOG("IDLE_1_CB\n"); + fprintf(stderr, "%s", "IDLE_1_CB\n"); + fflush(stderr); ASSERT(handle != NULL); ASSERT(idles_1_active > 0); @@ -164,7 +167,8 @@ static void idle_1_cb(uv_idle_t* handle) { static void idle_1_close_cb(uv_handle_t* handle) { - LOG("IDLE_1_CLOSE_CB\n"); + fprintf(stderr, "%s", "IDLE_1_CLOSE_CB\n"); + fflush(stderr); ASSERT(handle != NULL); @@ -173,7 +177,8 @@ static void idle_1_close_cb(uv_handle_t* handle) { static void prepare_1_close_cb(uv_handle_t* handle) { - LOG("PREPARE_1_CLOSE_CB"); + fprintf(stderr, "%s", "PREPARE_1_CLOSE_CB"); + fflush(stderr); ASSERT(handle == (uv_handle_t*)&prepare_1_handle); prepare_1_close_cb_called++; @@ -181,7 +186,8 @@ static void prepare_1_close_cb(uv_handle_t* handle) { static void check_close_cb(uv_handle_t* handle) { - LOG("CHECK_CLOSE_CB\n"); + fprintf(stderr, "%s", "CHECK_CLOSE_CB\n"); + fflush(stderr); ASSERT(handle == (uv_handle_t*)&check_handle); check_close_cb_called++; @@ -189,7 +195,8 @@ static void check_close_cb(uv_handle_t* handle) { static void prepare_2_close_cb(uv_handle_t* handle) { - LOG("PREPARE_2_CLOSE_CB\n"); + fprintf(stderr, "%s", "PREPARE_2_CLOSE_CB\n"); + fflush(stderr); ASSERT(handle == (uv_handle_t*)&prepare_2_handle); prepare_2_close_cb_called++; @@ -199,8 +206,8 @@ static void prepare_2_close_cb(uv_handle_t* handle) { static void check_cb(uv_check_t* handle) { int i, r; - LOG("CHECK_CB\n"); - + fprintf(stderr, "%s", "CHECK_CB\n"); + fflush(stderr); ASSERT(handle == &check_handle); if (loop_iteration < ITERATIONS) { @@ -235,8 +242,8 @@ static void check_cb(uv_check_t* handle) { static void prepare_2_cb(uv_prepare_t* handle) { int r; - LOG("PREPARE_2_CB\n"); - + fprintf(stderr, "%s", "PREPARE_2_CB\n"); + fflush(stderr); ASSERT(handle == &prepare_2_handle); /* prepare_2 gets started by prepare_1 when (loop_iteration % 2 == 0), */ @@ -255,8 +262,8 @@ static void prepare_2_cb(uv_prepare_t* handle) { static void prepare_1_cb(uv_prepare_t* handle) { int r; - LOG("PREPARE_1_CB\n"); - + fprintf(stderr, "%s", "PREPARE_1_CB\n"); + fflush(stderr); ASSERT(handle == &prepare_1_handle); if (loop_iteration % 2 == 0) { diff --git a/deps/uv/test/test-osx-select.c b/deps/uv/test/test-osx-select.c index 6ccf603483488a..a0afda9181ebd9 100644 --- a/deps/uv/test/test-osx-select.c +++ b/deps/uv/test/test-osx-select.c @@ -39,6 +39,7 @@ static void alloc_cb(uv_handle_t* handle, size_t size, uv_buf_t* buf) { static void read_cb(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) { fprintf(stdout, "got data %d\n", ++read_count); + fflush(stdout); if (read_count == 3) uv_close((uv_handle_t*) stream, NULL); @@ -55,7 +56,8 @@ TEST_IMPL(osx_select) { fd = open("/dev/tty", O_RDONLY); if (fd < 0) { - LOGF("Cannot open /dev/tty as read-only: %s\n", strerror(errno)); + fprintf(stderr, "Cannot open /dev/tty as read-only: %s\n", strerror(errno)); + fflush(stderr); return TEST_SKIP; } @@ -107,7 +109,8 @@ TEST_IMPL(osx_select_many_fds) { fd = open("/dev/tty", O_RDONLY); if (fd < 0) { - LOGF("Cannot open /dev/tty as read-only: %s\n", strerror(errno)); + fprintf(stderr, "Cannot open /dev/tty as read-only: %s\n", strerror(errno)); + fflush(stderr); return TEST_SKIP; } diff --git a/deps/uv/test/test-pipe-set-non-blocking.c b/deps/uv/test/test-pipe-set-non-blocking.c index 5cf2c19e7fbd29..fcc9fc0da85e99 100644 --- a/deps/uv/test/test-pipe-set-non-blocking.c +++ b/deps/uv/test/test-pipe-set-non-blocking.c @@ -88,8 +88,8 @@ TEST_IMPL(pipe_set_non_blocking) { uv_close((uv_handle_t*) &pipe_handle, NULL); ASSERT(0 == uv_run(uv_default_loop(), UV_RUN_DEFAULT)); - ASSERT(0 == close(fd[1])); /* fd[0] is closed by uv_close(). */ ASSERT(0 == uv_thread_join(&thread)); + ASSERT(0 == close(fd[1])); /* fd[0] is closed by uv_close(). */ uv_barrier_destroy(&ctx.barrier); MAKE_VALGRIND_HAPPY(); diff --git a/deps/uv/test/test-spawn.c b/deps/uv/test/test-spawn.c index 9b0030029c187c..d01862abe1d97a 100644 --- a/deps/uv/test/test-spawn.c +++ b/deps/uv/test/test-spawn.c @@ -21,6 +21,7 @@ #include "uv.h" #include "task.h" +#include #include #include #include @@ -34,6 +35,7 @@ # include #else # include +# include #endif @@ -180,6 +182,37 @@ TEST_IMPL(spawn_fails) { } +#ifndef _WIN32 +TEST_IMPL(spawn_fails_check_for_waitpid_cleanup) { + int r; + int status; + int err; + + init_process_options("", fail_cb); + options.file = options.args[0] = "program-that-had-better-not-exist"; + + r = uv_spawn(uv_default_loop(), &process, &options); + ASSERT(r == UV_ENOENT || r == UV_EACCES); + ASSERT(0 == uv_is_active((uv_handle_t*) &process)); + ASSERT(0 == uv_run(uv_default_loop(), UV_RUN_DEFAULT)); + + /* verify the child is successfully cleaned up within libuv */ + do + err = waitpid(process.pid, &status, 0); + while (err == -1 && errno == EINTR); + + ASSERT(err == -1); + ASSERT(errno == ECHILD); + + uv_close((uv_handle_t*) &process, NULL); + ASSERT(0 == uv_run(uv_default_loop(), UV_RUN_DEFAULT)); + + MAKE_VALGRIND_HAPPY(); + return 0; +} +#endif + + TEST_IMPL(spawn_exit_code) { int r; @@ -342,6 +375,163 @@ TEST_IMPL(spawn_stdout_and_stderr_to_file) { } +TEST_IMPL(spawn_stdout_and_stderr_to_file2) { +#ifndef _WIN32 + int r; + uv_file file; + uv_fs_t fs_req; + uv_stdio_container_t stdio[3]; + uv_buf_t buf; + + /* Setup. */ + unlink("stdout_file"); + + init_process_options("spawn_helper6", exit_cb); + + /* Replace stderr with our file */ + r = uv_fs_open(uv_default_loop(), + &fs_req, + "stdout_file", + O_CREAT | O_RDWR, + S_IRUSR | S_IWUSR, + NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&fs_req); + file = dup2(r, STDERR_FILENO); + ASSERT(file != -1); + + options.stdio = stdio; + options.stdio[0].flags = UV_IGNORE; + options.stdio[1].flags = UV_INHERIT_FD; + options.stdio[1].data.fd = file; + options.stdio[2].flags = UV_INHERIT_FD; + options.stdio[2].data.fd = file; + options.stdio_count = 3; + + r = uv_spawn(uv_default_loop(), &process, &options); + ASSERT(r == 0); + + r = uv_run(uv_default_loop(), UV_RUN_DEFAULT); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 1); + + buf = uv_buf_init(output, sizeof(output)); + r = uv_fs_read(uv_default_loop(), &fs_req, file, &buf, 1, 0, NULL); + ASSERT(r == 27); + uv_fs_req_cleanup(&fs_req); + + r = uv_fs_close(uv_default_loop(), &fs_req, file, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&fs_req); + + printf("output is: %s", output); + ASSERT(strcmp("hello world\nhello errworld\n", output) == 0); + + /* Cleanup. */ + unlink("stdout_file"); + + MAKE_VALGRIND_HAPPY(); + return 0; +#else + RETURN_SKIP("Unix only test"); +#endif +} + + +TEST_IMPL(spawn_stdout_and_stderr_to_file_swap) { +#ifndef _WIN32 + int r; + uv_file stdout_file; + uv_file stderr_file; + uv_fs_t fs_req; + uv_stdio_container_t stdio[3]; + uv_buf_t buf; + + /* Setup. */ + unlink("stdout_file"); + unlink("stderr_file"); + + init_process_options("spawn_helper6", exit_cb); + + /* open 'stdout_file' and replace STDOUT_FILENO with it */ + r = uv_fs_open(uv_default_loop(), + &fs_req, + "stdout_file", + O_CREAT | O_RDWR, + S_IRUSR | S_IWUSR, + NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&fs_req); + stdout_file = dup2(r, STDOUT_FILENO); + ASSERT(stdout_file != -1); + + /* open 'stderr_file' and replace STDERR_FILENO with it */ + r = uv_fs_open(uv_default_loop(), &fs_req, "stderr_file", O_CREAT | O_RDWR, + S_IRUSR | S_IWUSR, NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&fs_req); + stderr_file = dup2(r, STDERR_FILENO); + ASSERT(stderr_file != -1); + + /* now we're going to swap them: the child process' stdout will be our + * stderr_file and vice versa */ + options.stdio = stdio; + options.stdio[0].flags = UV_IGNORE; + options.stdio[1].flags = UV_INHERIT_FD; + options.stdio[1].data.fd = stderr_file; + options.stdio[2].flags = UV_INHERIT_FD; + options.stdio[2].data.fd = stdout_file; + options.stdio_count = 3; + + r = uv_spawn(uv_default_loop(), &process, &options); + ASSERT(r == 0); + + r = uv_run(uv_default_loop(), UV_RUN_DEFAULT); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 1); + + buf = uv_buf_init(output, sizeof(output)); + + /* check the content of stdout_file */ + r = uv_fs_read(uv_default_loop(), &fs_req, stdout_file, &buf, 1, 0, NULL); + ASSERT(r >= 15); + uv_fs_req_cleanup(&fs_req); + + r = uv_fs_close(uv_default_loop(), &fs_req, stdout_file, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&fs_req); + + printf("output is: %s", output); + ASSERT(strncmp("hello errworld\n", output, 15) == 0); + + /* check the content of stderr_file */ + r = uv_fs_read(uv_default_loop(), &fs_req, stderr_file, &buf, 1, 0, NULL); + ASSERT(r >= 12); + uv_fs_req_cleanup(&fs_req); + + r = uv_fs_close(uv_default_loop(), &fs_req, stderr_file, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&fs_req); + + printf("output is: %s", output); + ASSERT(strncmp("hello world\n", output, 12) == 0); + + /* Cleanup. */ + unlink("stdout_file"); + unlink("stderr_file"); + + MAKE_VALGRIND_HAPPY(); + return 0; +#else + RETURN_SKIP("Unix only test"); +#endif +} + + TEST_IMPL(spawn_stdin) { int r; uv_pipe_t out; @@ -1007,7 +1197,7 @@ TEST_IMPL(environment_creation) { return 0; } -// Regression test for issue #909 +/* Regression test for issue #909 */ TEST_IMPL(spawn_with_an_odd_path) { int r; diff --git a/deps/uv/test/test-tcp-write-fail.c b/deps/uv/test/test-tcp-write-fail.c new file mode 100644 index 00000000000000..2840d8161032be --- /dev/null +++ b/deps/uv/test/test-tcp-write-fail.c @@ -0,0 +1,115 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * 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. + */ + +#include "uv.h" +#include "task.h" +#include +#include +#ifndef _WIN32 +# include +#endif + + +static int connect_cb_called = 0; +static int write_cb_called = 0; +static int close_cb_called = 0; + +static uv_connect_t connect_req; +static uv_write_t write_req; + + +static void close_socket(uv_tcp_t* sock) { + uv_os_fd_t fd; + int r; + + r = uv_fileno((uv_handle_t*)sock, &fd); + ASSERT(r == 0); +#ifdef _WIN32 + r = closesocket(fd); +#else + r = close(fd); +#endif + ASSERT(r == 0); +} + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + + +static void write_cb(uv_write_t* req, int status) { + ASSERT(req != NULL); + + ASSERT(status != 0); + fprintf(stderr, "uv_write error: %s\n", uv_strerror(status)); + write_cb_called++; + + uv_close((uv_handle_t*)(req->handle), close_cb); +} + + +static void connect_cb(uv_connect_t* req, int status) { + uv_buf_t buf; + uv_stream_t* stream; + int r; + + ASSERT(req == &connect_req); + ASSERT(status == 0); + + stream = req->handle; + connect_cb_called++; + + /* close the socket, the hard way */ + close_socket((uv_tcp_t*)stream); + + buf = uv_buf_init("hello\n", 6); + r = uv_write(&write_req, stream, &buf, 1, write_cb); + ASSERT(r == 0); +} + + +TEST_IMPL(tcp_write_fail) { + struct sockaddr_in addr; + uv_tcp_t client; + int r; + + ASSERT(0 == uv_ip4_addr("127.0.0.1", TEST_PORT, &addr)); + + r = uv_tcp_init(uv_default_loop(), &client); + ASSERT(r == 0); + + r = uv_tcp_connect(&connect_req, + &client, + (const struct sockaddr*) &addr, + connect_cb); + ASSERT(r == 0); + + uv_run(uv_default_loop(), UV_RUN_DEFAULT); + + ASSERT(connect_cb_called == 1); + ASSERT(write_cb_called == 1); + ASSERT(close_cb_called == 1); + + MAKE_VALGRIND_HAPPY(); + return 0; +} diff --git a/deps/uv/test/test-timer-again.c b/deps/uv/test/test-timer-again.c index 095cd9e707baa8..f93c509be5dc0a 100644 --- a/deps/uv/test/test-timer-again.c +++ b/deps/uv/test/test-timer-again.c @@ -47,8 +47,9 @@ static void repeat_1_cb(uv_timer_t* handle) { ASSERT(handle == &repeat_1); ASSERT(uv_timer_get_repeat((uv_timer_t*)handle) == 50); - LOGF("repeat_1_cb called after %ld ms\n", - (long int)(uv_now(uv_default_loop()) - start_time)); + fprintf(stderr, "repeat_1_cb called after %ld ms\n", + (long int)(uv_now(uv_default_loop()) - start_time)); + fflush(stderr); repeat_1_cb_called++; @@ -69,8 +70,9 @@ static void repeat_2_cb(uv_timer_t* handle) { ASSERT(handle == &repeat_2); ASSERT(repeat_2_cb_allowed); - LOGF("repeat_2_cb called after %ld ms\n", - (long int)(uv_now(uv_default_loop()) - start_time)); + fprintf(stderr, "repeat_2_cb called after %ld ms\n", + (long int)(uv_now(uv_default_loop()) - start_time)); + fflush(stderr); repeat_2_cb_called++; @@ -80,8 +82,9 @@ static void repeat_2_cb(uv_timer_t* handle) { return; } - LOGF("uv_timer_get_repeat %ld ms\n", - (long int)uv_timer_get_repeat(&repeat_2)); + fprintf(stderr, "uv_timer_get_repeat %ld ms\n", + (long int)uv_timer_get_repeat(&repeat_2)); + fflush(stderr); ASSERT(uv_timer_get_repeat(&repeat_2) == 100); /* This shouldn't take effect immediately. */ @@ -129,8 +132,9 @@ TEST_IMPL(timer_again) { ASSERT(repeat_2_cb_called == 2); ASSERT(close_cb_called == 2); - LOGF("Test took %ld ms (expected ~700 ms)\n", - (long int)(uv_now(uv_default_loop()) - start_time)); + fprintf(stderr, "Test took %ld ms (expected ~700 ms)\n", + (long int)(uv_now(uv_default_loop()) - start_time)); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; diff --git a/deps/uv/test/test-tty.c b/deps/uv/test/test-tty.c index 7e1ce2668899f8..81e612c1d6ae1c 100644 --- a/deps/uv/test/test-tty.c +++ b/deps/uv/test/test-tty.c @@ -66,13 +66,15 @@ TEST_IMPL(tty) { #else /* unix */ ttyin_fd = open("/dev/tty", O_RDONLY, 0); if (ttyin_fd < 0) { - LOGF("Cannot open /dev/tty as read-only: %s\n", strerror(errno)); + fprintf(stderr, "Cannot open /dev/tty as read-only: %s\n", strerror(errno)); + fflush(stderr); return TEST_SKIP; } ttyout_fd = open("/dev/tty", O_WRONLY, 0); if (ttyout_fd < 0) { - LOGF("Cannot open /dev/tty as write-only: %s\n", strerror(errno)); + fprintf(stderr, "Cannot open /dev/tty as write-only: %s\n", strerror(errno)); + fflush(stderr); return TEST_SKIP; } #endif @@ -111,13 +113,20 @@ TEST_IMPL(tty) { ASSERT(height > 10); /* Turn on raw mode. */ - r = uv_tty_set_mode(&tty_in, 1); + r = uv_tty_set_mode(&tty_in, UV_TTY_MODE_RAW); ASSERT(r == 0); /* Turn off raw mode. */ - r = uv_tty_set_mode(&tty_in, 0); + r = uv_tty_set_mode(&tty_in, UV_TTY_MODE_NORMAL); ASSERT(r == 0); + /* Calling uv_tty_reset_mode() repeatedly should not clobber errno. */ + errno = 0; + ASSERT(0 == uv_tty_reset_mode()); + ASSERT(0 == uv_tty_reset_mode()); + ASSERT(0 == uv_tty_reset_mode()); + ASSERT(0 == errno); + /* TODO check the actual mode! */ uv_close((uv_handle_t*) &tty_in, NULL); @@ -128,3 +137,45 @@ TEST_IMPL(tty) { MAKE_VALGRIND_HAPPY(); return 0; } + + +TEST_IMPL(tty_file) { +#ifndef _WIN32 + uv_loop_t loop; + uv_tty_t tty; + int fd; + + ASSERT(0 == uv_loop_init(&loop)); + + fd = open("test/fixtures/empty_file", O_RDONLY); + if (fd != -1) { + ASSERT(UV_EINVAL == uv_tty_init(&loop, &tty, fd, 1)); + ASSERT(0 == close(fd)); + } + + fd = open("/dev/random", O_RDONLY); + if (fd != -1) { + ASSERT(UV_EINVAL == uv_tty_init(&loop, &tty, fd, 1)); + ASSERT(0 == close(fd)); + } + + fd = open("/dev/zero", O_RDONLY); + if (fd != -1) { + ASSERT(UV_EINVAL == uv_tty_init(&loop, &tty, fd, 1)); + ASSERT(0 == close(fd)); + } + + fd = open("/dev/tty", O_RDONLY); + if (fd != -1) { + ASSERT(0 == uv_tty_init(&loop, &tty, fd, 1)); + ASSERT(0 == close(fd)); + uv_close((uv_handle_t*) &tty, NULL); + } + + ASSERT(0 == uv_run(&loop, UV_RUN_DEFAULT)); + ASSERT(0 == uv_loop_close(&loop)); + + MAKE_VALGRIND_HAPPY(); +#endif + return 0; +} diff --git a/deps/uv/uv.gyp b/deps/uv/uv.gyp index 1ef8c05adc6496..acaed862d7c66e 100644 --- a/deps/uv/uv.gyp +++ b/deps/uv/uv.gyp @@ -39,7 +39,7 @@ '_FILE_OFFSET_BITS=64', ], }], - ['OS == "mac"', { + ['OS in "mac ios"', { 'defines': [ '_DARWIN_USE_64_BIT_INODE=1' ], }], ['OS == "linux"', { @@ -167,18 +167,17 @@ 'cflags': [ '-fPIC' ], }], ['uv_library=="shared_library" and OS!="mac"', { - 'link_settings': { - # Must correspond with UV_VERSION_MAJOR and UV_VERSION_MINOR - # in include/uv-version.h - 'libraries': [ '-Wl,-soname,libuv.so.1.0' ], - }, + # This will cause gyp to set soname + # Must correspond with UV_VERSION_MAJOR + # in include/uv-version.h + 'product_extension': 'so.1', }], ], }], - [ 'OS in "linux mac android"', { + [ 'OS in "linux mac ios android"', { 'sources': [ 'src/unix/proctitle.c' ], }], - [ 'OS=="mac"', { + [ 'OS in "mac ios"', { 'sources': [ 'src/unix/darwin.c', 'src/unix/fsevents.c', @@ -261,7 +260,7 @@ 'libraries': [ '-lkvm' ], }, }], - [ 'OS in "mac freebsd dragonflybsd openbsd netbsd".split()', { + [ 'OS in "ios mac freebsd dragonflybsd openbsd netbsd".split()', { 'sources': [ 'src/unix/kqueue.c' ], }], ['uv_library=="shared_library"', { @@ -364,6 +363,7 @@ 'test/test-tcp-write-to-half-open-connection.c', 'test/test-tcp-write-after-connect.c', 'test/test-tcp-writealot.c', + 'test/test-tcp-write-fail.c', 'test/test-tcp-try-write.c', 'test/test-tcp-unexpected-read.c', 'test/test-tcp-oob.c', diff --git a/deps/uv/vcbuild.bat b/deps/uv/vcbuild.bat index d3b7aa154eec6a..084ab9578fe10d 100644 --- a/deps/uv/vcbuild.bat +++ b/deps/uv/vcbuild.bat @@ -90,8 +90,8 @@ if defined noprojgen goto msbuild @rem Generate the VS project. if exist build\gyp goto have_gyp -echo git clone https://git.chromium.org/external/gyp.git build/gyp -git clone https://git.chromium.org/external/gyp.git build/gyp +echo git clone https://chromium.googlesource.com/external/gyp build/gyp +git clone https://chromium.googlesource.com/external/gyp build/gyp if errorlevel 1 goto gyp_install_failed goto have_gyp diff --git a/doc/api/tls.markdown b/doc/api/tls.markdown index 38649b55085313..e2922558040ef5 100644 --- a/doc/api/tls.markdown +++ b/doc/api/tls.markdown @@ -141,14 +141,37 @@ automatically set as a listener for the [secureConnection][] event. The - `ciphers`: A string describing the ciphers to use or exclude, seperated by `:`. The default cipher suite is: - ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256: - DHE-RSA-AES256-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256: - HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA - - The default cipher suite prefers ECDHE and DHE ciphers for Perfect Forward - secrecy, while offering *some* backward compatibiltity. Old clients which - rely on insecure and deprecated RC4 or DES-based ciphers (like Internet - Explorer 6) aren't able to complete the handshake with the default + ECDHE-RSA-AES128-GCM-SHA256: + ECDHE-ECDSA-AES128-GCM-SHA256: + ECDHE-RSA-AES256-GCM-SHA384: + ECDHE-ECDSA-AES256-GCM-SHA384: + DHE-RSA-AES128-GCM-SHA256: + ECDHE-RSA-AES128-SHA256: + DHE-RSA-AES128-SHA256: + ECDHE-RSA-AES256-SHA384: + DHE-RSA-AES256-SHA384: + ECDHE-RSA-AES256-SHA256: + DHE-RSA-AES256-SHA256: + HIGH: + !aNULL: + !eNULL: + !EXPORT: + !DES: + !RC4: + !MD5: + !PSK: + !SRP: + !CAMELLIA + + The default cipher suite prefers GCM ciphers for [Chrome's 'modern + cryptography' setting] and also prefers ECDHE and DHE ciphers for Perfect + Forward secrecy, while offering *some* backward compatibiltity. + + 128 bit AES is preferred over 192 and 256 bit AES in light of [specific + attacks affecting larger AES key sizes]. + + Old clients that rely on insecure and deprecated RC4 or DES-based ciphers + (like Internet Explorer 6) aren't able to complete the handshake with the default configuration. If you absolutely must support these clients, the [TLS recommendations] may offer a compatible cipher suite. For more details on the format, see the [OpenSSL cipher list format documentation]. @@ -160,8 +183,10 @@ automatically set as a listener for the [secureConnection][] event. The - `dhparam`: A string or `Buffer` containing Diffie Hellman parameters, required for Perfect Forward Secrecy. Use `openssl dhparam` to create it. - If omitted or invalid, it is silently discarded and DHE ciphers won't be - available. + Its key length should be greater than or equal to 1024 bits, otherwise + it throws an error. It is strongly recommended to use 2048 bits or + more for stronger security. If omitted or invalid, it is silently + discarded and DHE ciphers won't be available. - `handshakeTimeout`: Abort the connection if the SSL/TLS handshake does not finish in this many milliseconds. The default is 120 seconds. @@ -784,6 +809,8 @@ The string representation of the local IP address. The numeric representation of the local port. [OpenSSL cipher list format documentation]: http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT +[Chrome's 'modern cryptography' setting]: http://www.chromium.org/Home/chromium-security/education/tls#TOC-Deprecation-of-TLS-Features-Algorithms-in-Chrome +[specific attacks affecting larger AES key sizes]: https://www.schneier.com/blog/archives/2009/07/another_new_aes.html [BEAST attacks]: http://blog.ivanristic.com/2011/10/mitigating-the-beast-attack-on-tls.html [tls.createServer]: #tls_tls_createserver_options_secureconnectionlistener [tls.createSecurePair]: #tls_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized diff --git a/doc/api/v8.markdown b/doc/api/v8.markdown index adced82685eea4..cedd5c86d9b008 100644 --- a/doc/api/v8.markdown +++ b/doc/api/v8.markdown @@ -20,7 +20,7 @@ Returns an object with the following properties } ``` -## setFlagsFromString() +## setFlagsFromString(string) Set additional V8 command line flags. Use with care; changing settings after the VM has started may result in unpredictable behavior, including diff --git a/lib/_debugger.js b/lib/_debugger.js index f1885b2e32f467..4c503d2f5480e9 100644 --- a/lib/_debugger.js +++ b/lib/_debugger.js @@ -101,7 +101,7 @@ Protocol.prototype.execute = function(d) { if (len - this.bodyStartByteIndex < this.contentLength) { break; } - // pass thru + // falls through case 'body': var resRawByteLength = Buffer.byteLength(res.raw, 'utf8'); @@ -125,7 +125,6 @@ Protocol.prototype.execute = function(d) { default: throw new Error('Unknown state'); - break; } }; @@ -262,7 +261,7 @@ Client.prototype.req = function(req, cb) { Client.prototype.reqVersion = function(cb) { cb = cb || function() {}; - this.req({ command: 'version' } , function(err, body, res) { + this.req({ command: 'version' }, function(err, body, res) { if (err) return cb(err); cb(null, res.body.body.V8Version, res.body.running); }); @@ -398,7 +397,7 @@ Client.prototype.reqFrameEval = function(expression, frame, cb) { // reqBacktrace(cb) // TODO: from, to, bottom Client.prototype.reqBacktrace = function(cb) { - this.req({ command: 'backtrace', arguments: { inlineRefs: true } } , cb); + this.req({ command: 'backtrace', arguments: { inlineRefs: true } }, cb); }; @@ -432,7 +431,7 @@ Client.prototype.reqScripts = function(cb) { var self = this; cb = cb || function() {}; - this.req({ command: 'scripts' } , function(err, res) { + this.req({ command: 'scripts' }, function(err, res) { if (err) return cb(err); for (var i = 0; i < res.length; i++) { diff --git a/lib/_http_incoming.js b/lib/_http_incoming.js index 41ece371cdfbe6..aea665e80973c9 100644 --- a/lib/_http_incoming.js +++ b/lib/_http_incoming.js @@ -137,8 +137,10 @@ IncomingMessage.prototype._addHeaderLine = function(field, value, dest) { } break; + /* eslint-disable max-len */ // list is taken from: // https://mxr.mozilla.org/mozilla/source/netwerk/protocol/http/src/nsHttpHeaderArray.cpp + /* eslint-enable max-len */ case 'content-type': case 'content-length': case 'user-agent': @@ -158,9 +160,9 @@ IncomingMessage.prototype._addHeaderLine = function(field, value, dest) { default: // make comma-separated list - if (dest[field] !== undefined) + if (dest[field] !== undefined) { dest[field] += ', ' + value; - else { + } else { dest[field] = value; } } diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 88590551c9defb..bfebef21b69af6 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -85,8 +85,9 @@ OutgoingMessage.prototype.setTimeout = function(msecs, callback) { this.once('socket', function(socket) { socket.setTimeout(msecs); }); - } else + } else { this.socket.setTimeout(msecs); + } }; diff --git a/lib/_http_server.js b/lib/_http_server.js index 99903024c26d14..ae2bba035c8763 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -221,9 +221,11 @@ function Server(requestListener) { this.addListener('request', requestListener); } + /* eslint-disable max-len */ // Similar option to this. Too lazy to write my own docs. // http://www.squid-cache.org/Doc/config/half_closed_clients/ // http://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F + /* eslint-enable max-len */ this.httpAllowHalfOpen = false; this.addListener('connection', connectionListener); diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index 1de55597123d1b..bebbc80e2bf8dc 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -234,8 +234,9 @@ function howMuchToRead(n, state) { if (!state.ended) { state.needReadable = true; return 0; - } else + } else { return state.length; + } } return n; @@ -774,7 +775,7 @@ Readable.prototype.wrap = function(stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function(method) { return function() { return stream[method].apply(stream, arguments); - }}(i); + }; }(i); } } diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index da65ddb90ae5ca..54f751abdf24ee 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -9,7 +9,6 @@ Writable.WritableState = WritableState; const util = require('util'); const Stream = require('stream'); -const debug = util.debuglog('stream'); util.inherits(Writable, Stream); @@ -273,9 +272,9 @@ function writeOrBuffer(stream, state, chunk, encoding, cb) { } else { state.bufferedRequest = state.lastBufferedRequest; } - } - else + } else { doWrite(stream, state, false, len, chunk, encoding, cb); + } return ret; } @@ -471,8 +470,9 @@ function finishMaybe(stream, state) { prefinish(stream, state); state.finished = true; stream.emit('finish'); - } else + } else { prefinish(stream, state); + } } return need; } diff --git a/lib/_tls_legacy.js b/lib/_tls_legacy.js index 3348d7f92d951c..0a0c7bca7b9024 100644 --- a/lib/_tls_legacy.js +++ b/lib/_tls_legacy.js @@ -646,7 +646,7 @@ function onnewsession(key, session) { if (self.ssl) self.ssl.newSessionDone(); - }; + } } diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 122c7042a4cf2f..5a35c3bd967b55 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -141,29 +141,23 @@ function onclienthello(hello) { if (err) return self.destroy(err); - // Servername came from SSL session - // NOTE: TLS Session ticket doesn't include servername information - // - // Another note, From RFC3546: - // - // If, on the other hand, the older - // session is resumed, then the server MUST ignore extensions appearing - // in the client hello, and send a server hello containing no - // extensions; in this case the extension functionality negotiated - // during the original session initiation is applied to the resumed - // session. - // - // Therefore we should account session loading when dealing with servername - var servername = session && session.servername || hello.servername; - loadSNI(self, servername, function(err, ctx) { + self._handle.endParser(); + }); +} + + +function oncertcb(info) { + var self = this; + var servername = info.servername; + + loadSNI(self, servername, function(err, ctx) { + if (err) + return self.destroy(err); + requestOCSP(self, info, ctx, function(err) { if (err) return self.destroy(err); - requestOCSP(self, hello, ctx, function(err) { - if (err) - return self.destroy(err); - self._handle.endParser(); - }); + self._handle.certCbDone(); }); }); } @@ -295,15 +289,22 @@ TLSSocket.prototype._wrapHandle = function(handle) { } }); - this.on('close', this._destroySSL); + this.on('close', function() { + this._destroySSL(); + res = null; + }); return res; }; TLSSocket.prototype._destroySSL = function _destroySSL() { + if (!this.ssl) return; this.ssl.destroySSL(); - if (this.ssl._secureContext.singleUse) + if (this.ssl._secureContext.singleUse) { this.ssl._secureContext.context.close(); + this.ssl._secureContext.context = null; + } + this.ssl = null; }; TLSSocket.prototype._init = function(socket, wrap) { @@ -333,15 +334,18 @@ TLSSocket.prototype._init = function(socket, wrap) { ssl.onhandshakestart = onhandshakestart.bind(this); ssl.onhandshakedone = onhandshakedone.bind(this); ssl.onclienthello = onclienthello.bind(this); + ssl.oncertcb = oncertcb.bind(this); ssl.onnewsession = onnewsession.bind(this); ssl.lastHandshakeTime = 0; ssl.handshakes = 0; - if (this.server && - (listenerCount(this.server, 'resumeSession') > 0 || - listenerCount(this.server, 'newSession') > 0 || - listenerCount(this.server, 'OCSPRequest') > 0)) { - ssl.enableSessionCallbacks(); + if (this.server) { + if (listenerCount(this.server, 'resumeSession') > 0 || + listenerCount(this.server, 'newSession') > 0) { + ssl.enableSessionCallbacks(); + } + if (listenerCount(this.server, 'OCSPRequest') > 0) + ssl.enableCertCb(); } } else { ssl.onhandshakestart = function() {}; @@ -358,7 +362,7 @@ TLSSocket.prototype._init = function(socket, wrap) { self._writableState.errorEmitted = true; // Destroy socket if error happened before handshake's finish - if (!this._secureEstablished) { + if (!self._secureEstablished) { self._tlsError(err); self.destroy(); } else if (options.isServer && @@ -382,7 +386,7 @@ TLSSocket.prototype._init = function(socket, wrap) { options.server._contexts.length)) { assert(typeof options.SNICallback === 'function'); this._SNICallback = options.SNICallback; - ssl.enableHelloParser(); + ssl.enableCertCb(); } if (process.features.tls_npn && options.NPNProtocols) diff --git a/lib/assert.js b/lib/assert.js index 4a01e5c7f0b356..70e784a50c34b9 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -323,4 +323,4 @@ assert.doesNotThrow = function(block, /*optional*/message) { _throws.apply(this, [false].concat(pSlice.call(arguments))); }; -assert.ifError = function(err) { if (err) {throw err;}}; +assert.ifError = function(err) { if (err) throw err; }; diff --git a/lib/buffer.js b/lib/buffer.js index 8f4e34d289fc27..dc2b656d7a7a33 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -247,6 +247,11 @@ Buffer.concat = function(list, length) { if (!Array.isArray(list)) throw new TypeError('list argument must be an Array of Buffers.'); + if (list.length === 0) + return new Buffer(0); + else if (list.length === 1) + return list[0]; + if (length === undefined) { length = 0; for (var i = 0; i < list.length; i++) @@ -255,11 +260,6 @@ Buffer.concat = function(list, length) { length = length >>> 0; } - if (list.length === 0) - return new Buffer(0); - else if (list.length === 1) - return list[0]; - var buffer = new Buffer(length); var pos = 0; for (var i = 0; i < list.length; i++) { diff --git a/lib/child_process.js b/lib/child_process.js index 99da7cfbde94dc..34ce359f5b0ec5 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -169,7 +169,7 @@ SocketListSend.prototype._request = function(msg, cmd, callback) { function onclose() { self.slave.removeListener('internalMessage', onreply); callback(new Error('Slave closed before reply')); - }; + } function onreply(msg) { if (!(msg.cmd === cmd && msg.key === self.key)) return; @@ -177,7 +177,7 @@ SocketListSend.prototype._request = function(msg, cmd, callback) { self.slave.removeListener('internalMessage', onreply); callback(null, msg); - }; + } this.slave.once('disconnect', onclose); this.slave.on('internalMessage', onreply); diff --git a/lib/cluster.js b/lib/cluster.js index 10a55996f15cc8..ca1005b738068f 100644 --- a/lib/cluster.js +++ b/lib/cluster.js @@ -11,7 +11,7 @@ const SCHED_RR = 2; const uv = process.binding('uv'); -const cluster = new EventEmitter; +const cluster = new EventEmitter(); module.exports = cluster; cluster.Worker = Worker; cluster.isWorker = ('NODE_UNIQUE_ID' in process.env); @@ -127,11 +127,10 @@ RoundRobinHandle.prototype.add = function(worker, send) { function done() { if (self.handle.getsockname) { var out = {}; - var err = self.handle.getsockname(out); + self.handle.getsockname(out); // TODO(bnoordhuis) Check err. send(null, { sockname: out }, null); - } - else { + } else { send(null, null, null); // UNIX socket. } self.handoff(worker); // In case there are connections pending. @@ -196,7 +195,7 @@ else function masterInit() { cluster.workers = {}; - var intercom = new EventEmitter; + var intercom = new EventEmitter(); cluster.settings = {}; // XXX(bnoordhuis) Fold cluster.schedulingPolicy into cluster.settings? @@ -511,6 +510,7 @@ function workerInit() { }); cluster.worker = worker; process.once('disconnect', function() { + worker.emit('disconnect'); if (!worker.suicide) { // Unexpected disconnect, master exited, or some such nastiness, so // worker exits immediately. diff --git a/lib/console.js b/lib/console.js index 63e3c5e0bf1aa4..f9032e24a0fa44 100644 --- a/lib/console.js +++ b/lib/console.js @@ -73,7 +73,7 @@ Console.prototype.timeEnd = function(label) { Console.prototype.trace = function trace() { // TODO probably can to do this better with V8's debug object once that is // exposed. - var err = new Error; + var err = new Error(); err.name = 'Trace'; err.message = util.format.apply(this, arguments); Error.captureStackTrace(err, trace); diff --git a/lib/crypto.js b/lib/crypto.js index 10ff71e8547606..7ce89482d54b14 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -320,7 +320,7 @@ function Verify(algorithm, options) { if (!(this instanceof Verify)) return new Verify(algorithm, options); - this._handle = new binding.Verify; + this._handle = new binding.Verify(); this._handle.init(algorithm); stream.Writable.call(this, options); diff --git a/lib/dgram.js b/lib/dgram.js index 7d2592819a8e87..1cce233eab808b 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -39,13 +39,13 @@ function lookup6(address, callback) { function newHandle(type) { if (type == 'udp4') { - var handle = new UDP; + var handle = new UDP(); handle.lookup = lookup4; return handle; } if (type == 'udp6') { - var handle = new UDP; + var handle = new UDP(); handle.lookup = lookup6; handle.bind = handle.bind6; handle.send = handle.send6; @@ -301,8 +301,7 @@ Socket.prototype.send = function(buffer, if (ex) { if (callback) callback(ex); self.emit('error', ex); - } - else if (self._handle) { + } else if (self._handle) { var req = new SendWrap(); req.buffer = buffer; // Keep reference alive. req.length = length; @@ -338,7 +337,10 @@ function afterSend(err) { if (err) { err = exceptionWithHostPort(err, 'send', this.address, this.port); } - this.callback(err, this.length); + var self = this; + setImmediate(function() { + self.callback(err, self.length); + }); } diff --git a/lib/dns.js b/lib/dns.js index 9334800e4da5c4..28f1607b44ece2 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -239,7 +239,7 @@ function resolver(bindingName) { if (err) throw errnoException(err, bindingName); callback.immediately = true; return req; - } + }; } diff --git a/lib/events.js b/lib/events.js index 064f3838b38ac9..3ea798b3bdb01a 100644 --- a/lib/events.js +++ b/lib/events.js @@ -140,7 +140,10 @@ EventEmitter.prototype.emit = function emit(type) { } else if (er instanceof Error) { throw er; // Unhandled 'error' event } else { - throw new Error('Uncaught, unspecified "error" event.'); + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; } return false; } @@ -307,8 +310,9 @@ EventEmitter.prototype.removeListener = if (--this._eventsCount === 0) { this._events = {}; return this; - } else + } else { delete events[type]; + } } else { spliceOne(list, position); } diff --git a/lib/fs.js b/lib/fs.js index b6b62265403ee8..4cdd0ef5e31456 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -40,7 +40,7 @@ function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. if (DEBUG) { - var backtrace = new Error; + var backtrace = new Error(); return function(err) { if (err) { backtrace.stack = err.name + ': ' + err.message + diff --git a/lib/net.js b/lib/net.js index 847e417e67f4ca..b261196119a9ed 100644 --- a/lib/net.js +++ b/lib/net.js @@ -201,6 +201,7 @@ function onSocketFinish() { var req = new ShutdownWrap(); req.oncomplete = afterShutdown; + req.handle = this._handle; var err = this._handle.shutdown(req); if (err) @@ -430,7 +431,7 @@ Socket.prototype._destroy = function(exception, cb) { }); self._writableState.errorEmitted = true; } - }; + } if (this.destroyed) { debug('already destroyed, fire error callbacks'); @@ -627,6 +628,7 @@ Socket.prototype._writeGeneric = function(writev, data, encoding, cb) { } var req = new WriteWrap(); + req.handle = this._handle; req.oncomplete = afterWrite; req.async = false; var err; @@ -1319,7 +1321,7 @@ Server.prototype.listen = function() { Server.prototype.address = function() { if (this._handle && this._handle.getsockname) { var out = {}; - var err = this._handle.getsockname(out); + this._handle.getsockname(out); // TODO(bnoordhuis) Check err and throw? return out; } else if (this._pipeName) { diff --git a/lib/querystring.js b/lib/querystring.js index 09220a919e3edc..6aa188725ae25a 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -28,7 +28,7 @@ QueryString.unescapeBuffer = function(s, decodeSpaces) { break; case charCode('+'): if (decodeSpaces) c = charCode(' '); - // pass thru + // falls through default: out[outIndex++] = c; break; diff --git a/lib/readline.js b/lib/readline.js index a6845010dae661..5b9637b6f5455a 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -883,15 +883,25 @@ exports.Interface = Interface; * accepts a readable Stream instance and makes it emit "keypress" events */ +const KEYPRESS_DECODER = Symbol('keypress-decoder'); +const ESCAPE_DECODER = Symbol('escape-decoder'); + function emitKeypressEvents(stream) { - if (stream._keypressDecoder) return; + if (stream[KEYPRESS_DECODER]) return; var StringDecoder = require('string_decoder').StringDecoder; // lazy load - stream._keypressDecoder = new StringDecoder('utf8'); + stream[KEYPRESS_DECODER] = new StringDecoder('utf8'); + + stream[ESCAPE_DECODER] = emitKeys(stream); + stream[ESCAPE_DECODER].next(); function onData(b) { if (EventEmitter.listenerCount(stream, 'keypress') > 0) { - var r = stream._keypressDecoder.write(b); - if (r) emitKeys(stream, r); + var r = stream[KEYPRESS_DECODER].write(b); + if (r) { + for (var i = 0; i < r.length; i++) { + stream[ESCAPE_DECODER].next(r[i]); + } + } } else { // Nobody's watching anyway stream.removeListener('data', onData); @@ -944,102 +954,130 @@ exports.emitKeypressEvents = emitKeypressEvents; // Regexes used for ansi escape code splitting const metaKeyCodeReAnywhere = /(?:\x1b)([a-zA-Z0-9])/; -const metaKeyCodeRe = new RegExp('^' + metaKeyCodeReAnywhere.source + '$'); const functionKeyCodeReAnywhere = new RegExp('(?:\x1b+)(O|N|\\[|\\[\\[)(?:' + [ '(\\d+)(?:;(\\d+))?([~^$])', '(?:M([@ #!a`])(.)(.))', // mouse '(?:1;)?(\\d+)?([a-zA-Z])' ].join('|') + ')'); -const functionKeyCodeRe = new RegExp('^' + functionKeyCodeReAnywhere.source); -const escapeCodeReAnywhere = new RegExp([ - functionKeyCodeReAnywhere.source, metaKeyCodeReAnywhere.source, /\x1b./.source -].join('|')); - -function emitKeys(stream, s) { - if (s instanceof Buffer) { - if (s[0] > 127 && s[1] === undefined) { - s[0] -= 128; - s = '\x1b' + s.toString(stream.encoding || 'utf-8'); - } else { - s = s.toString(stream.encoding || 'utf-8'); - } - } - var buffer = []; - var match; - while (match = escapeCodeReAnywhere.exec(s)) { - buffer = buffer.concat(s.slice(0, match.index).split('')); - buffer.push(match[0]); - s = s.slice(match.index + match[0].length); - } - buffer = buffer.concat(s.split('')); - - buffer.forEach(function(s) { - var ch, - key = { - sequence: s, - name: undefined, - ctrl: false, - meta: false, - shift: false - }, - parts; - - if (s === '\r') { - // carriage return - key.name = 'return'; - } else if (s === '\n') { - // enter, should have been called linefeed - key.name = 'enter'; +function* emitKeys(stream) { + while (true) { + var ch = yield; + var s = ch; + var escaped = false; + var key = { + sequence: null, + name: undefined, + ctrl: false, + meta: false, + shift: false + }; + + if (ch === '\x1b') { + escaped = true; + s += (ch = yield); + + if (ch === '\x1b') { + s += (ch = yield); + } + } - } else if (s === '\t') { - // tab - key.name = 'tab'; + if (escaped && (ch === 'O' || ch === '[')) { + // ansi escape sequence + var code = ch; + var modifier = 0; - } else if (s === '\b' || s === '\x7f' || - s === '\x1b\x7f' || s === '\x1b\b') { - // backspace or ctrl+h - key.name = 'backspace'; - key.meta = (s.charAt(0) === '\x1b'); + if (ch === 'O') { + // ESC O letter + // ESC O modifier letter + s += (ch = yield); - } else if (s === '\x1b' || s === '\x1b\x1b') { - // escape key - key.name = 'escape'; - key.meta = (s.length === 2); + if (ch >= '0' && ch <= '9') { + modifier = (ch >> 0) - 1; + s += (ch = yield); + } - } else if (s === ' ' || s === '\x1b ') { - key.name = 'space'; - key.meta = (s.length === 2); + code += ch; - } else if (s.length === 1 && s <= '\x1a') { - // ctrl+letter - key.name = String.fromCharCode(s.charCodeAt(0) + 'a'.charCodeAt(0) - 1); - key.ctrl = true; + } else if (ch === '[') { + // ESC [ letter + // ESC [ modifier letter + // ESC [ [ modifier letter + // ESC [ [ num char + s += (ch = yield); - } else if (s.length === 1 && s >= 'a' && s <= 'z') { - // lowercase letter - key.name = s; + if (ch === '[') { + // \x1b[[A + // ^--- escape codes might have a second bracket + code += ch; + s += (ch = yield); + } - } else if (s.length === 1 && s >= 'A' && s <= 'Z') { - // shift+letter - key.name = s.toLowerCase(); - key.shift = true; + /* + * Here and later we try to buffer just enough data to get + * a complete ascii sequence. + * + * We have basically two classes of ascii characters to process: + * + * + * 1. `\x1b[24;5~` should be parsed as { code: '[24~', modifier: 5 } + * + * This particular example is featuring Ctrl+F12 in xterm. + * + * - `;5` part is optional, e.g. it could be `\x1b[24~` + * - first part can contain one or two digits + * + * So the generic regexp is like /^\d\d?(;\d)?[~^$]$/ + * + * + * 2. `\x1b[1;5H` should be parsed as { code: '[H', modifier: 5 } + * + * This particular example is featuring Ctrl+Home in xterm. + * + * - `1;5` part is optional, e.g. it could be `\x1b[H` + * - `1;` part is optional, e.g. it could be `\x1b[5H` + * + * So the generic regexp is like /^((\d;)?\d)?[A-Za-z]$/ + * + */ + const cmdStart = s.length - 1; + + // skip one or two leading digits + if (ch >= '0' && ch <= '9') { + s += (ch = yield); + + if (ch >= '0' && ch <= '9') { + s += (ch = yield); + } + } - } else if (parts = metaKeyCodeRe.exec(s)) { - // meta+character key - key.name = parts[1].toLowerCase(); - key.meta = true; - key.shift = /^[A-Z]$/.test(parts[1]); + // skip modifier + if (ch === ';') { + s += (ch = yield); - } else if (parts = functionKeyCodeRe.exec(s)) { - // ansi escape sequence + if (ch >= '0' && ch <= '9') { + s += (ch = yield); + } + } - // reassemble the key code leaving out leading \x1b's, - // the modifier key bitflag and any meaningless "1;" sequence - var code = (parts[1] || '') + (parts[2] || '') + - (parts[4] || '') + (parts[9] || ''), - modifier = (parts[3] || parts[8] || 1) - 1; + /* + * We buffered enough data, now trying to extract code + * and modifier from it + */ + const cmd = s.slice(cmdStart); + var match; + + if ((match = cmd.match(/^(\d\d?)(;(\d))?([~^$])$/))) { + code += match[1] + match[4]; + modifier = (match[3] || 1) - 1; + } else if ((match = cmd.match(/^((\d;)?(\d))?([A-Za-z])$/))) { + code += match[4]; + modifier = (match[3] || 1) - 1; + } else { + code += cmd; + } + } // Parse the key modifier key.ctrl = !!(modifier & 4); @@ -1142,23 +1180,58 @@ function emitKeys(stream, s) { /* misc. */ case '[Z': key.name = 'tab'; key.shift = true; break; default: key.name = 'undefined'; break; - } - } - // Don't emit a key if no name was found - if (key.name === undefined) { - key = undefined; - } + } else if (ch === '\r') { + // carriage return + key.name = 'return'; + + } else if (ch === '\n') { + // enter, should have been called linefeed + key.name = 'enter'; + + } else if (ch === '\t') { + // tab + key.name = 'tab'; - if (s.length === 1) { - ch = s; + } else if (ch === '\b' || ch === '\x7f') { + // backspace or ctrl+h + key.name = 'backspace'; + key.meta = escaped; + + } else if (ch === '\x1b') { + // escape key + key.name = 'escape'; + key.meta = escaped; + + } else if (ch === ' ') { + key.name = 'space'; + key.meta = escaped; + + } else if (!escaped && ch <= '\x1a') { + // ctrl+letter + key.name = String.fromCharCode(ch.charCodeAt(0) + 'a'.charCodeAt(0) - 1); + key.ctrl = true; + + } else if (/^[0-9A-Za-z]$/.test(ch)) { + // letter, number, shift+letter + key.name = ch.toLowerCase(); + key.shift = /^[A-Z]$/.test(ch); + key.meta = escaped; } - if (key || ch) { - stream.emit('keypress', ch, key); + key.sequence = s; + + if (key.name !== undefined) { + /* Named character or sequence */ + stream.emit('keypress', escaped ? undefined : s, key); + } else if (s.length === 1) { + /* Single unnamed character, e.g. "." */ + stream.emit('keypress', s); + } else { + /* Unrecognized or broken escape sequence, don't emit anything */ } - }); + } } diff --git a/lib/repl.js b/lib/repl.js index 036b561f9c2a94..ddf3fecdfd56ea 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -318,7 +318,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { // Display prompt again self.displayPrompt(); - }; + } }); self.on('SIGCONT', function() { diff --git a/lib/tls.js b/lib/tls.js index 3ae7a8f58b11a1..10c82860ba826e 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -15,12 +15,17 @@ exports.CLIENT_RENEG_WINDOW = 600; exports.SLAB_BUFFER_SIZE = 10 * 1024 * 1024; exports.DEFAULT_CIPHERS = [ + 'ECDHE-RSA-AES128-GCM-SHA256', + 'ECDHE-ECDSA-AES128-GCM-SHA256', + 'ECDHE-RSA-AES256-GCM-SHA384', + 'ECDHE-ECDSA-AES256-GCM-SHA384', + 'DHE-RSA-AES128-GCM-SHA256', + 'ECDHE-RSA-AES128-SHA256', + 'DHE-RSA-AES128-SHA256', 'ECDHE-RSA-AES256-SHA384', 'DHE-RSA-AES256-SHA384', 'ECDHE-RSA-AES256-SHA256', 'DHE-RSA-AES256-SHA256', - 'ECDHE-RSA-AES128-SHA256', - 'DHE-RSA-AES128-SHA256', 'HIGH', '!aNULL', '!eNULL', diff --git a/lib/url.js b/lib/url.js index 1683f905037c52..8da2f025dc8ca2 100644 --- a/lib/url.js +++ b/lib/url.js @@ -80,7 +80,7 @@ const querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url instanceof Url) return url; - var u = new Url; + var u = new Url(); u.parse(url, parseQueryString, slashesDenoteHost); return u; } diff --git a/lib/util.js b/lib/util.js index a04c19c7353fdf..4dbc59376dcefe 100644 --- a/lib/util.js +++ b/lib/util.js @@ -12,6 +12,8 @@ exports.format = function(f) { return objects.join(' '); } + if (arguments.length === 1) return f; + var i = 1; var args = arguments; var len = args.length; @@ -27,6 +29,7 @@ exports.format = function(f) { } catch (_) { return '[Circular]'; } + // falls through default: return x; } diff --git a/src/async-wrap-inl.h b/src/async-wrap-inl.h index b08f791c2e7635..0518cd3b7ce002 100644 --- a/src/async-wrap-inl.h +++ b/src/async-wrap-inl.h @@ -17,43 +17,30 @@ inline AsyncWrap::AsyncWrap(Environment* env, v8::Handle<:object> object, ProviderType provider, AsyncWrap* parent) - : BaseObject(env, object), bits_(static_cast(provider) << 1) { + : BaseObject(env, object, provider), + bits_(static_cast(provider) << 1) { // Check user controlled flag to see if the init callback should run. if (!env->using_asyncwrap()) return; - if (!env->call_async_init_hook() && parent == nullptr) - return; - // TODO(trevnorris): Until it's verified all passed object's are not weak, - // add a HandleScope to make sure there's no leak. - v8::HandleScope scope(env->isolate()); + // If callback hooks have not been enabled, and there is no parent, return. + if (!env->async_wrap_callbacks_enabled() && parent == nullptr) + return; - v8::Local<:object> parent_obj; + // If callback hooks have not been enabled and parent has no queue, return. + if (!env->async_wrap_callbacks_enabled() && !parent->has_async_queue()) + return; + v8::HandleScope scope(env->isolate()); v8::TryCatch try_catch; - // If a parent value was sent then call its pre/post functions to let it know - // a conceptual "child" is being instantiated (e.g. that a server has - // received a connection). - if (parent != nullptr) { - parent_obj = parent->object(); - env->async_hooks_pre_function()->Call(parent_obj, 0, nullptr); - if (try_catch.HasCaught()) - FatalError("node::AsyncWrap::AsyncWrap", "parent pre hook threw"); - } - - env->async_hooks_init_function()->Call(object, 0, nullptr); + v8::Local<:value> n = v8::Int32::New(env->isolate(), provider); + env->async_hooks_init_function()->Call(object, 1, &n); if (try_catch.HasCaught()) FatalError("node::AsyncWrap::AsyncWrap", "init hook threw"); bits_ |= 1; // has_async_queue() is true now. - - if (parent != nullptr) { - env->async_hooks_post_function()->Call(parent_obj, 0, nullptr); - if (try_catch.HasCaught()) - FatalError("node::AsyncWrap::AsyncWrap", "parent post hook threw"); - } } diff --git a/src/async-wrap.cc b/src/async-wrap.cc index 5710c43146060b..2da6b102934fa7 100644 --- a/src/async-wrap.cc +++ b/src/async-wrap.cc @@ -23,32 +23,28 @@ using v8::kExternalUint32Array; namespace node { +static void EnableHooksJS(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + env->async_hooks()->set_enable_callbacks(1); +} + + +static void DisableHooksJS(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + env->async_hooks()->set_enable_callbacks(0); +} + + static void SetupHooks(const FunctionCallbackInfo& args) { - Environment* env = Environment::GetCurrent(args.GetIsolate()); + Environment* env = Environment::GetCurrent(args); - CHECK(args[0]->IsObject()); + CHECK(args[0]->IsFunction()); CHECK(args[1]->IsFunction()); CHECK(args[2]->IsFunction()); - CHECK(args[3]->IsFunction()); - - // Attach Fields enum from Environment::AsyncHooks. - // Flags attached to this object are: - // - kCallInitHook (0): Tells the AsyncWrap constructor whether it should - // make a call to the init JS callback. This is disabled by default, so - // even after setting the callbacks the flag will have to be set to - // non-zero to have those callbacks called. This only affects the init - // callback. If the init callback was called, then the pre/post callbacks - // will automatically be called. - Local async_hooks_obj = args[0].As(); - Environment::AsyncHooks* async_hooks = env->async_hooks(); - async_hooks_obj->SetIndexedPropertiesToExternalArrayData( - async_hooks->fields(), - kExternalUint32Array, - async_hooks->fields_count()); - - env->set_async_hooks_init_function(args[1].As()); - env->set_async_hooks_pre_function(args[2].As()); - env->set_async_hooks_post_function(args[3].As()); + + env->set_async_hooks_init_function(args[0].As()); + env->set_async_hooks_pre_function(args[1].As()); + env->set_async_hooks_post_function(args[2].As()); env->set_using_asyncwrap(true); } @@ -61,7 +57,9 @@ static void Initialize(Handle target, Isolate* isolate = env->isolate(); HandleScope scope(isolate); - NODE_SET_METHOD(target, "setupHooks", SetupHooks); + env->SetMethod(target, "setupHooks", SetupHooks); + env->SetMethod(target, "disable", DisableHooksJS); + env->SetMethod(target, "enable", EnableHooksJS); Local async_providers = Object::New(isolate); #define V(PROVIDER) \ diff --git a/src/base-object-inl.h b/src/base-object-inl.h index db0daa1e82f559..775b07342edee9 100644 --- a/src/base-object-inl.h +++ b/src/base-object-inl.h @@ -10,10 +10,15 @@ namespace node { -inline BaseObject::BaseObject(Environment* env, v8::Local<:object> handle) +inline BaseObject::BaseObject(Environment* env, + v8::Local<:object> handle, + const uint16_t class_id) : handle_(env->isolate(), handle), env_(env) { CHECK_EQ(false, handle.IsEmpty()); + // Shift value 8 bits over to try avoiding conflict with anything else. + if (class_id != 0) + handle_.SetWrapperClassId(class_id << 8); } diff --git a/src/base-object.h b/src/base-object.h index 5a7b95827e8f11..90abee4333fcb1 100644 --- a/src/base-object.h +++ b/src/base-object.h @@ -9,7 +9,9 @@ class Environment; class BaseObject { public: - BaseObject(Environment* env, v8::Local<:object> handle); + BaseObject(Environment* env, + v8::Local<:object> handle, + const uint16_t class_id = 0); virtual ~BaseObject(); // Returns the wrapped object. Returns an empty handle when diff --git a/src/env-inl.h b/src/env-inl.h index 237da7159d1ecf..a0815acaccb926 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -66,8 +66,12 @@ inline int Environment::AsyncHooks::fields_count() const { return kFieldsCount; } -inline bool Environment::AsyncHooks::call_init_hook() { - return fields_[kCallInitHook] != 0; +inline bool Environment::AsyncHooks::callbacks_enabled() { + return fields_[kEnableCallbacks] != 0; +} + +inline void Environment::AsyncHooks::set_enable_callbacks(uint32_t flag) { + fields_[kEnableCallbacks] = flag; } inline Environment::DomainFlag::DomainFlag() { @@ -214,9 +218,9 @@ inline v8::Isolate* Environment::isolate() const { return isolate_; } -inline bool Environment::call_async_init_hook() const { +inline bool Environment::async_wrap_callbacks_enabled() const { // The const_cast is okay, it doesn't violate conceptual const-ness. - return const_cast(this)->async_hooks()->call_init_hook(); + return const_cast(this)->async_hooks()->callbacks_enabled(); } inline bool Environment::in_domain() const { diff --git a/src/env.h b/src/env.h index 9099b3b931717a..e327786e36b907 100644 --- a/src/env.h +++ b/src/env.h @@ -55,6 +55,7 @@ namespace node { V(bytes_parsed_string, "bytesParsed") \ V(callback_string, "callback") \ V(change_string, "change") \ + V(oncertcb_string, "oncertcb") \ V(onclose_string, "_onclose") \ V(code_string, "code") \ V(compare_string, "compare") \ @@ -268,7 +269,8 @@ class Environment { public: inline uint32_t* fields(); inline int fields_count() const; - inline bool call_init_hook(); + inline bool callbacks_enabled(); + inline void set_enable_callbacks(uint32_t flag); private: friend class Environment; // So we can call the constructor. @@ -276,7 +278,7 @@ class Environment { enum Fields { // Set this to not zero if the init hook should be called. - kCallInitHook, + kEnableCallbacks, kFieldsCount }; @@ -373,7 +375,7 @@ class Environment { inline v8::Isolate* isolate() const; inline uv_loop_t* event_loop() const; - inline bool call_async_init_hook() const; + inline bool async_wrap_callbacks_enabled() const; inline bool in_domain() const; inline uint32_t watched_providers() const; diff --git a/src/js_stream.cc b/src/js_stream.cc index 7fcdfd9a94d9fd..6b7c4063e05a2a 100644 --- a/src/js_stream.cc +++ b/src/js_stream.cc @@ -71,6 +71,7 @@ int JSStream::DoShutdown(ShutdownWrap* req_wrap) { req_wrap->object() }; + req_wrap->Dispatched(); Local res = MakeCallback(env()->onshutdown_string(), ARRAY_SIZE(argv), argv); @@ -88,13 +89,14 @@ int JSStream::DoWrite(WriteWrap* w, Local bufs_arr = Array::New(env()->isolate(), count); for (size_t i = 0; i < count; i++) - bufs_arr->Set(i, Buffer::New(env(), bufs[0].base, bufs[0].len)); + bufs_arr->Set(i, Buffer::New(env(), bufs[i].base, bufs[i].len)); Local argv[] = { w->object(), bufs_arr }; + w->Dispatched(); Local res = MakeCallback(env()->onwrite_string(), ARRAY_SIZE(argv), argv); diff --git a/src/node.h b/src/node.h index 28b40aa0721b3a..acdfe5740740ef 100644 --- a/src/node.h +++ b/src/node.h @@ -42,7 +42,35 @@ #include "v8.h" // NOLINT(build/include_order) #include "node_version.h" // NODE_MODULE_VERSION -#define NODE_DEPRECATED(msg, fn) V8_DEPRECATED(msg, fn) +#define IOJS_MAKE_VERSION(major, minor, patch) \ + ((major) * 0x1000 + (minor) * 0x100 + (patch)) + +#ifdef __clang__ +# define IOJS_CLANG_AT_LEAST(major, minor, patch) \ + (IOJS_MAKE_VERSION(major, minor, patch) <= \ + IOJS_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__)) +#else +# define IOJS_CLANG_AT_LEAST(major, minor, patch) (0) +#endif + +#ifdef __GNUC__ +# define IOJS_GNUC_AT_LEAST(major, minor, patch) \ + (IOJS_MAKE_VERSION(major, minor, patch) <= \ + IOJS_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)) +#else +# define IOJS_GNUC_AT_LEAST(major, minor, patch) (0) +#endif + +#if IOJS_CLANG_AT_LEAST(2, 9, 0) || IOJS_GNUC_AT_LEAST(4, 5, 0) +# define NODE_DEPRECATED(message, declarator) \ + __attribute__((deprecated(message))) declarator +#elif defined(_MSC_VER) +# define NODE_DEPRECATED(message, declarator) \ + __declspec(deprecated) declarator +#else +# define NODE_DEPRECATED(message, declarator) \ + declarator +#endif // Forward-declare libuv loop struct uv_loop_s; @@ -237,9 +265,10 @@ inline void NODE_SET_PROTOTYPE_METHOD(v8::Handle<:functiontemplate> recv, #define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD enum encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; -enum encoding ParseEncoding(v8::Isolate* isolate, - v8::Handle<:value> encoding_v, - enum encoding default_encoding = BINARY); +NODE_EXTERN enum encoding ParseEncoding( + v8::Isolate* isolate, + v8::Handle<:value> encoding_v, + enum encoding default_encoding = BINARY); NODE_DEPRECATED("Use ParseEncoding(isolate, ...)", inline enum encoding ParseEncoding( v8::Handle<:value> encoding_v, diff --git a/src/node.js b/src/node.js index e4167cb2d1cfbf..e3285cd2220690 100644 --- a/src/node.js +++ b/src/node.js @@ -82,16 +82,9 @@ delete process.env.NODE_UNIQUE_ID; } - // Load any preload modules - if (process._preload_modules) { - var Module = NativeModule.require('module'); - process._preload_modules.forEach(function(module) { - Module._load(module); - }); - } - if (process._eval != null) { // User passed '-e' or '--eval' arguments to Node. + startup.preloadModules(); evalScript('[eval]'); } else if (process.argv[1]) { // make process.argv[1] into a full path @@ -99,7 +92,7 @@ process.argv[1] = path.resolve(process.argv[1]); var Module = NativeModule.require('module'); - + startup.preloadModules(); if (global.v8debug && process.execArgv.some(function(arg) { return arg.match(/^--debug-brk(=[0-9]*)?$/); @@ -329,22 +322,33 @@ // Run callbacks that have no domain. // Using domains will cause this to be overridden. function _tickCallback() { - var callback, threw, tock; + var callback, args, tock; do { while (tickInfo[kIndex] < tickInfo[kLength]) { tock = nextTickQueue[tickInfo[kIndex]++]; callback = tock.callback; - threw = true; - try { - if (tock.args === undefined) - callback(); - else - callback.apply(null, tock.args); - threw = false; - } finally { - if (threw) - tickDone(); + args = tock.args; + // Using separate callback execution functions helps to limit the + // scope of DEOPTs caused by using try blocks and allows direct + // callback invocation with small numbers of arguments to avoid the + // performance hit associated with using `fn.apply()` + if (args === undefined) { + doNTCallback0(callback); + } else { + switch (args.length) { + case 1: + doNTCallback1(callback, args[0]); + break; + case 2: + doNTCallback2(callback, args[0], args[1]); + break; + case 3: + doNTCallback3(callback, args[0], args[1], args[2]); + break; + default: + doNTCallbackMany(callback, args); + } } if (1e4 < tickInfo[kIndex]) tickDone(); @@ -356,25 +360,36 @@ } function _tickDomainCallback() { - var callback, domain, threw, tock; + var callback, domain, args, tock; do { while (tickInfo[kIndex] < tickInfo[kLength]) { tock = nextTickQueue[tickInfo[kIndex]++]; callback = tock.callback; domain = tock.domain; + args = tock.args; if (domain) domain.enter(); - threw = true; - try { - if (tock.args === undefined) - callback(); - else - callback.apply(null, tock.args); - threw = false; - } finally { - if (threw) - tickDone(); + // Using separate callback execution functions helps to limit the + // scope of DEOPTs caused by using try blocks and allows direct + // callback invocation with small numbers of arguments to avoid the + // performance hit associated with using `fn.apply()` + if (args === undefined) { + doNTCallback0(callback); + } else { + switch (args.length) { + case 1: + doNTCallback1(callback, args[0]); + break; + case 2: + doNTCallback2(callback, args[0], args[1]); + break; + case 3: + doNTCallback3(callback, args[0], args[1], args[2]); + break; + default: + doNTCallbackMany(callback, args); + } } if (1e4 < tickInfo[kIndex]) tickDone(); @@ -387,6 +402,61 @@ } while (tickInfo[kLength] !== 0); } + function doNTCallback0(callback) { + var threw = true; + try { + callback(); + threw = false; + } finally { + if (threw) + tickDone(); + } + } + + function doNTCallback1(callback, arg1) { + var threw = true; + try { + callback(arg1); + threw = false; + } finally { + if (threw) + tickDone(); + } + } + + function doNTCallback2(callback, arg1, arg2) { + var threw = true; + try { + callback(arg1, arg2); + threw = false; + } finally { + if (threw) + tickDone(); + } + } + + function doNTCallback3(callback, arg1, arg2, arg3) { + var threw = true; + try { + callback(arg1, arg2, arg3); + threw = false; + } finally { + if (threw) + tickDone(); + } + } + + function doNTCallbackMany(callback, args) { + var threw = true; + try { + callback.apply(null, args); + threw = false; + } finally { + if (threw) + tickDone(); + } + } + function TickObject(c, args) { this.callback = c; this.domain = process.domain || null; @@ -398,7 +468,7 @@ if (process._exiting) return; - var args = undefined; + var args; if (arguments.length > 1) { args = []; for (var i = 1; i < arguments.length; i++) @@ -419,8 +489,9 @@ if (!process.emit('unhandledRejection', reason, promise)) { // Nobody is listening. // TODO(petkaantonov) Take some default action, see #830 - } else + } else { hadListeners = true; + } } } return hadListeners; @@ -779,6 +850,16 @@ }; }; + // Load preload modules + startup.preloadModules = function() { + if (process._preload_modules) { + var Module = NativeModule.require('module'); + process._preload_modules.forEach(function(module) { + Module._load(module); + }); + } + }; + // Below you find a minimal module system, which is used to load the node // core modules found in lib/*.js. All core modules are compiled into the // node binary, so they can be loaded faster. diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 8a473847f285f2..bd02279212583a 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -98,7 +98,7 @@ Local New(Isolate* isolate, Handle string, enum encoding enc) { size_t length = StringBytes::Size(isolate, string, enc); - Local buf = New(length); + Local buf = New(isolate, length); char* data = Buffer::Data(buf); StringBytes::Write(isolate, data, length, string, enc); diff --git a/src/node_crypto.cc b/src/node_crypto.cc index 1d112001e88a0b..44c43b72a0e937 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -132,6 +132,8 @@ template int SSLWrap::SelectNextProtoCallback( #endif template int SSLWrap::TLSExtStatusCallback(SSL* s, void* arg); template void SSLWrap::DestroySSL(); +template int SSLWrap::SSLCertCallback(SSL* s, void* arg); +template void SSLWrap::WaitForCertCb(CertCb cb, void* arg); static void crypto_threadid_cb(CRYPTO_THREADID* tid) { @@ -511,7 +513,8 @@ int SSL_CTX_use_certificate_chain(SSL_CTX* ctx, } while ((ca = PEM_read_bio_X509(in, nullptr, CryptoPemCallback, nullptr))) { - r = SSL_CTX_add_extra_chain_cert(ctx, ca); + // NOTE: Increments reference count on `ca` + r = SSL_CTX_add1_chain_cert(ctx, ca); if (!r) { X509_free(ca); @@ -754,6 +757,12 @@ void SecureContext::SetDHParam(const FunctionCallbackInfo& args) { if (dh == nullptr) return; + const int keylen = BN_num_bits(dh->p); + if (keylen < 1024) + return env->ThrowError("DH parameter is less than 1024 bits"); + else if (keylen < 2048) + fprintf(stderr, "WARNING: DH parameter is less than 2048 bits\n"); + SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_DH_USE); int r = SSL_CTX_set_tmp_dh(sc->ctx_, dh); DH_free(dh); @@ -987,6 +996,7 @@ void SSLWrap::AddMethods(Environment* env, Handle t) { env->SetProtoMethod(t, "verifyError", VerifyError); env->SetProtoMethod(t, "getCurrentCipher", GetCurrentCipher); env->SetProtoMethod(t, "endParser", EndParser); + env->SetProtoMethod(t, "certCbDone", CertCbDone); env->SetProtoMethod(t, "renegotiate", Renegotiate); env->SetProtoMethod(t, "shutdownSSL", Shutdown); env->SetProtoMethod(t, "getTLSTicket", GetTLSTicket); @@ -1869,6 +1879,122 @@ int SSLWrap::TLSExtStatusCallback(SSL* s, void* arg) { #endif // NODE__HAVE_TLSEXT_STATUS_CB +template +void SSLWrap::WaitForCertCb(CertCb cb, void* arg) { + cert_cb_ = cb; + cert_cb_arg_ = arg; +} + + +template +int SSLWrap::SSLCertCallback(SSL* s, void* arg) { + Base* w = static_cast(SSL_get_app_data(s)); + + if (!w->is_server()) + return 1; + + if (!w->is_waiting_cert_cb()) + return 1; + + if (w->cert_cb_running_) + return -1; + + Environment* env = w->env(); + HandleScope handle_scope(env->isolate()); + Context::Scope context_scope(env->context()); + w->cert_cb_running_ = true; + + Local info = Object::New(env->isolate()); + + SSL_SESSION* sess = SSL_get_session(s); + if (sess != nullptr) { + if (sess->tlsext_hostname == nullptr) { + info->Set(env->servername_string(), String::Empty(env->isolate())); + } else { + Local servername = OneByteString(env->isolate(), + sess->tlsext_hostname, + strlen(sess->tlsext_hostname)); + info->Set(env->servername_string(), servername); + } + info->Set(env->tls_ticket_string(), + Boolean::New(env->isolate(), sess->tlsext_ticklen != 0)); + } + bool ocsp = s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp; + info->Set(env->ocsp_request_string(), Boolean::New(env->isolate(), ocsp)); + + Local argv[] = { info }; + w->MakeCallback(env->oncertcb_string(), ARRAY_SIZE(argv), argv); + + if (!w->cert_cb_running_) + return 1; + + // Performing async action, wait... + return -1; +} + + +template +void SSLWrap::CertCbDone(const FunctionCallbackInfo& args) { + Base* w = Unwrap(args.Holder()); + Environment* env = w->env(); + + CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_); + + Local object = w->object(); + Local ctx = object->Get(env->sni_context_string()); + Local cons = env->secure_context_constructor_template(); + + // Not an object, probably undefined or null + if (!ctx->IsObject()) + goto fire_cb; + + if (cons->HasInstance(ctx)) { + SecureContext* sc = Unwrap(ctx.As()); + w->sni_context_.Reset(); + w->sni_context_.Reset(env->isolate(), ctx); + + int rv; + + // NOTE: reference count is not increased by this API methods + X509* x509 = SSL_CTX_get0_certificate(sc->ctx_); + EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_); + STACK_OF(X509)* chain; + + rv = SSL_CTX_get0_chain_certs(sc->ctx_, &chain); + if (rv) + rv = SSL_use_certificate(w->ssl_, x509); + if (rv) + rv = SSL_use_PrivateKey(w->ssl_, pkey); + if (rv && chain != nullptr) + rv = SSL_set1_chain(w->ssl_, chain); + if (!rv) { + unsigned long err = ERR_get_error(); + if (!err) + return env->ThrowError("CertCbDone"); + return ThrowCryptoError(env, err); + } + } else { + // Failure: incorrect SNI context object + Local err = Exception::TypeError(env->sni_context_err_string()); + w->MakeCallback(env->onerror_string(), 1, &err); + return; + } + + fire_cb: + CertCb cb; + void* arg; + + cb = w->cert_cb_; + arg = w->cert_cb_arg_; + + w->cert_cb_running_ = false; + w->cert_cb_ = nullptr; + w->cert_cb_arg_ = nullptr; + + cb(arg); +} + + template void SSLWrap::SSLGetter(Local property, const PropertyCallbackInfo& info) { @@ -1975,6 +2101,10 @@ int Connection::HandleSSLError(const char* func, DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func); return 0; + } else if (err == SSL_ERROR_WANT_X509_LOOKUP) { + DEBUG_PRINT("[%p] SSL: %s want x509 lookup\n", ssl_, func); + return 0; + } else if (err == SSL_ERROR_ZERO_RETURN) { HandleScope scope(ssl_env()->isolate()); @@ -2140,7 +2270,7 @@ int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) { // Call the SNI callback and use its return value as context if (!conn->sniObject_.IsEmpty()) { - conn->sniContext_.Reset(); + conn->sni_context_.Reset(); Local arg = PersistentToLocal(env->isolate(), conn->servername_); Local ret = conn->MakeCallback(env->onselect_string(), 1, &arg); @@ -2149,7 +2279,7 @@ int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) { Local secure_context_constructor_template = env->secure_context_constructor_template(); if (secure_context_constructor_template->HasInstance(ret)) { - conn->sniContext_.Reset(env->isolate(), ret); + conn->sni_context_.Reset(env->isolate(), ret); SecureContext* sc = Unwrap(ret.As()); InitNPN(sc); SSL_set_SSL_CTX(s, sc->ctx_); @@ -2188,6 +2318,8 @@ void Connection::New(const FunctionCallbackInfo& args) { InitNPN(sc); + SSL_set_cert_cb(conn->ssl_, SSLWrap::SSLCertCallback, conn); + #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB if (is_server) { SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_); @@ -4613,7 +4745,7 @@ void RandomBytesCheck(RandomBytesRequest* req, Local argv[2]) { size_t size; req->return_memory(&data, &size); argv[0] = Null(req->env()->isolate()); - argv[1] = Buffer::Use(data, size); + argv[1] = Buffer::Use(req->env()->isolate(), data, size); } } diff --git a/src/node_crypto.h b/src/node_crypto.h index f6069f88410c0b..179543bd50124a 100644 --- a/src/node_crypto.h +++ b/src/node_crypto.h @@ -143,7 +143,10 @@ class SSLWrap { kind_(kind), next_sess_(nullptr), session_callbacks_(false), - new_session_wait_(false) { + new_session_wait_(false), + cert_cb_(nullptr), + cert_cb_arg_(nullptr), + cert_cb_running_(false) { ssl_ = SSL_new(sc->ctx_); env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize); CHECK_NE(ssl_, nullptr); @@ -160,6 +163,9 @@ class SSLWrap { npn_protos_.Reset(); selected_npn_proto_.Reset(); #endif +#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB + sni_context_.Reset(); +#endif #ifdef NODE__HAVE_TLSEXT_STATUS_CB ocsp_response_.Reset(); #endif // NODE__HAVE_TLSEXT_STATUS_CB @@ -170,8 +176,11 @@ class SSLWrap { inline bool is_server() const { return kind_ == kServer; } inline bool is_client() const { return kind_ == kClient; } inline bool is_waiting_new_session() const { return new_session_wait_; } + inline bool is_waiting_cert_cb() const { return cert_cb_ != nullptr; } protected: + typedef void (*CertCb)(void* arg); + // Size allocated by OpenSSL: one for SSL structure, one for SSL3_STATE and // some for buffers. // NOTE: Actually it is much more than this @@ -199,6 +208,7 @@ class SSLWrap { static void VerifyError(const v8::FunctionCallbackInfo<:value>& args); static void GetCurrentCipher(const v8::FunctionCallbackInfo<:value>& args); static void EndParser(const v8::FunctionCallbackInfo<:value>& args); + static void CertCbDone(const v8::FunctionCallbackInfo<:value>& args); static void Renegotiate(const v8::FunctionCallbackInfo<:value>& args); static void Shutdown(const v8::FunctionCallbackInfo<:value>& args); static void GetTLSTicket(const v8::FunctionCallbackInfo<:value>& args); @@ -227,10 +237,12 @@ class SSLWrap { void* arg); #endif // OPENSSL_NPN_NEGOTIATED static int TLSExtStatusCallback(SSL* s, void* arg); + static int SSLCertCallback(SSL* s, void* arg); static void SSLGetter(v8::Local<:string> property, const v8::PropertyCallbackInfo<:value>& info); void DestroySSL(); + void WaitForCertCb(CertCb cb, void* arg); inline Environment* ssl_env() const { return env_; @@ -242,6 +254,12 @@ class SSLWrap { SSL* ssl_; bool session_callbacks_; bool new_session_wait_; + + // SSL_set_cert_cb + CertCb cert_cb_; + void* cert_cb_arg_; + bool cert_cb_running_; + ClientHelloParser hello_parser_; #ifdef NODE__HAVE_TLSEXT_STATUS_CB @@ -253,6 +271,10 @@ class SSLWrap { v8::Persistent<:value> selected_npn_proto_; #endif // OPENSSL_NPN_NEGOTIATED +#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB + v8::Persistent<:value> sni_context_; +#endif + friend class SecureContext; }; @@ -264,7 +286,6 @@ class Connection : public SSLWrap, public AsyncWrap { ~Connection() override { #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB sniObject_.Reset(); - sniContext_.Reset(); servername_.Reset(); #endif } @@ -279,7 +300,6 @@ class Connection : public SSLWrap, public AsyncWrap { #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB v8::Persistent<:object> sniObject_; - v8::Persistent<:value> sniContext_; v8::Persistent<:string> servername_; #endif diff --git a/src/node_http_parser.cc b/src/node_http_parser.cc index f71302d3130a16..6c5d76ecf6cc95 100644 --- a/src/node_http_parser.cc +++ b/src/node_http_parser.cc @@ -554,7 +554,9 @@ const struct http_parser_settings Parser::settings = { Parser::on_header_value, Parser::on_headers_complete, Parser::on_body, - Parser::on_message_complete + Parser::on_message_complete, + nullptr, // on_chunk_header + nullptr // on_chunk_complete }; diff --git a/src/node_v8.cc b/src/node_v8.cc index f3bdda409d0f6e..2834a21496bbdb 100644 --- a/src/node_v8.cc +++ b/src/node_v8.cc @@ -60,6 +60,13 @@ void GetHeapStatistics(const FunctionCallbackInfo& args) { void SetFlagsFromString(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + + if (args.Length() < 1) + return env->ThrowTypeError("v8 flag is required"); + if (!args[0]->IsString()) + return env->ThrowTypeError("v8 flag must be a string"); + String::Utf8Value flags(args[0]); V8::SetFlagsFromString(*flags, flags.length()); } diff --git a/src/spawn_sync.cc b/src/spawn_sync.cc index b014bae40dffc9..901a4a001df051 100644 --- a/src/spawn_sync.cc +++ b/src/spawn_sync.cc @@ -165,9 +165,9 @@ void SyncProcessStdioPipe::Close() { } -Local SyncProcessStdioPipe::GetOutputAsBuffer() const { +Local SyncProcessStdioPipe::GetOutputAsBuffer(Isolate* isolate) const { size_t length = OutputLength(); - Local js_buffer = Buffer::New(length); + Local js_buffer = Buffer::New(isolate, length); CopyOutput(Buffer::Data(js_buffer)); return js_buffer; } @@ -679,7 +679,7 @@ Local SyncProcessRunner::BuildOutputArray() { for (uint32_t i = 0; i < stdio_count_; i++) { SyncProcessStdioPipe* h = stdio_pipes_[i]; if (h != nullptr && h->writable()) - js_output->Set(i, h->GetOutputAsBuffer()); + js_output->Set(i, h->GetOutputAsBuffer(env()->isolate())); else js_output->Set(i, Null(env()->isolate())); } diff --git a/src/spawn_sync.h b/src/spawn_sync.h index 4a71b75202b5b2..9a544fa0576402 100644 --- a/src/spawn_sync.h +++ b/src/spawn_sync.h @@ -72,7 +72,7 @@ class SyncProcessStdioPipe { int Start(); void Close(); - Local GetOutputAsBuffer() const; + Local GetOutputAsBuffer(Isolate* isolate) const; inline bool readable() const; inline bool writable() const; diff --git a/src/stream_base.cc b/src/stream_base.cc index 3a9f30f279bd2c..b2518404a8fe62 100644 --- a/src/stream_base.cc +++ b/src/stream_base.cc @@ -60,7 +60,6 @@ int StreamBase::Shutdown(const FunctionCallbackInfo& args) { AfterShutdown); int err = DoShutdown(req_wrap); - req_wrap->Dispatched(); if (err) delete req_wrap; return err; @@ -181,7 +180,6 @@ int StreamBase::Writev(const FunctionCallbackInfo& args) { if (bufs != bufs_) delete[] bufs; - req_wrap->Dispatched(); req_wrap->object()->Set(env->async(), True(env->isolate())); req_wrap->object()->Set(env->bytes_string(), Number::New(env->isolate(), bytes)); @@ -228,7 +226,6 @@ int StreamBase::WriteBuffer(const FunctionCallbackInfo& args) { req_wrap = WriteWrap::New(env, req_wrap_obj, this, AfterWrite); err = DoWrite(req_wrap, bufs, count, nullptr); - req_wrap->Dispatched(); req_wrap_obj->Set(env->async(), True(env->isolate())); if (err) @@ -347,7 +344,6 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { reinterpret_cast(send_handle)); } - req_wrap->Dispatched(); req_wrap->object()->Set(env->async(), True(env->isolate())); if (err) diff --git a/src/stream_wrap.cc b/src/stream_wrap.cc index be5757d4a60bd1..540639d458050c 100644 --- a/src/stream_wrap.cc +++ b/src/stream_wrap.cc @@ -279,7 +279,10 @@ void StreamWrap::SetBlocking(const FunctionCallbackInfo& args) { int StreamWrap::DoShutdown(ShutdownWrap* req_wrap) { - return uv_shutdown(&req_wrap->req_, stream(), AfterShutdown); + int err; + err = uv_shutdown(&req_wrap->req_, stream(), AfterShutdown); + req_wrap->Dispatched(); + return err; } @@ -353,6 +356,7 @@ int StreamWrap::DoWrite(WriteWrap* w, } } + w->Dispatched(); UpdateWriteQueueSize(); return r; diff --git a/src/tls_wrap.cc b/src/tls_wrap.cc index c013bf935eb9cb..30768640eb99e2 100644 --- a/src/tls_wrap.cc +++ b/src/tls_wrap.cc @@ -150,6 +150,8 @@ void TLSWrap::InitSSL() { InitNPN(sc_); + SSL_set_cert_cb(ssl_, SSLWrap::SSLCertCallback, this); + if (is_server()) { SSL_set_accept_state(ssl_); } else if (is_client()) { @@ -309,7 +311,6 @@ void TLSWrap::EncOut() { for (size_t i = 0; i < count; i++) buf[i] = uv_buf_init(data[i], size[i]); int err = stream_->DoWrite(write_req, buf, count, nullptr); - write_req->Dispatched(); // Ignore errors, this should be already handled in js if (err) { @@ -351,11 +352,16 @@ void TLSWrap::EncOutCb(WriteWrap* req_wrap, int status) { Local TLSWrap::GetSSLError(int status, int* err, const char** msg) { EscapableHandleScope scope(env()->isolate()); + // ssl_ is already destroyed in reading EOF by close notify alert. + if (ssl_ == nullptr) + return Local(); + *err = SSL_get_error(ssl_, status); switch (*err) { case SSL_ERROR_NONE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: + case SSL_ERROR_WANT_X509_LOOKUP: break; case SSL_ERROR_ZERO_RETURN: return scope.Escape(env()->zero_return_string()); @@ -430,7 +436,10 @@ void TLSWrap::ClearOut() { OnRead(UV_EOF, nullptr); } - if (read == -1) { + // We need to check whether an error occurred or the connection was + // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0. + // See iojs#1642 and SSL_read(3SSL) for details. + if (read <= 0) { int err; Local arg = GetSSLError(read, &err, nullptr); @@ -565,6 +574,7 @@ int TLSWrap::DoWrite(WriteWrap* w, // Queue callback to execute it on next tick write_item_queue_.PushBack(new WriteItem(w)); + w->Dispatched(); // Write queued data if (empty) { @@ -738,12 +748,6 @@ void TLSWrap::EnableSessionCallbacks( const FunctionCallbackInfo& args) { TLSWrap* wrap = Unwrap(args.Holder()); wrap->enable_session_callbacks(); - EnableHelloParser(args); -} - - -void TLSWrap::EnableHelloParser(const FunctionCallbackInfo& args) { - TLSWrap* wrap = Unwrap(args.Holder()); NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength); wrap->hello_parser_.Start(SSLWrap::OnClientHello, OnClientHelloParseEnd, @@ -759,6 +763,12 @@ void TLSWrap::DestroySSL(const FunctionCallbackInfo& args) { } +void TLSWrap::EnableCertCb(const FunctionCallbackInfo& args) { + TLSWrap* wrap = Unwrap(args.Holder()); + wrap->WaitForCertCb(OnClientHelloParseEnd, wrap); +} + + void TLSWrap::OnClientHelloParseEnd(void* arg) { TLSWrap* c = static_cast(arg); c->Cycle(); @@ -857,8 +867,8 @@ void TLSWrap::Initialize(Handle target, env->SetProtoMethod(t, "start", Start); env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode); env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks); - env->SetProtoMethod(t, "enableHelloParser", EnableHelloParser); env->SetProtoMethod(t, "destroySSL", DestroySSL); + env->SetProtoMethod(t, "enableCertCb", EnableCertCb); StreamBase::AddMethods(env, t, StreamBase::kFlagHasWritev); SSLWrap::AddMethods(env, t); diff --git a/src/tls_wrap.h b/src/tls_wrap.h index 25088d30261189..a30447519083c2 100644 --- a/src/tls_wrap.h +++ b/src/tls_wrap.h @@ -130,7 +130,7 @@ class TLSWrap : public crypto::SSLWrap, static void SetVerifyMode(const v8::FunctionCallbackInfo<:value>& args); static void EnableSessionCallbacks( const v8::FunctionCallbackInfo<:value>& args); - static void EnableHelloParser( + static void EnableCertCb( const v8::FunctionCallbackInfo<:value>& args); static void DestroySSL(const v8::FunctionCallbackInfo<:value>& args); @@ -159,10 +159,6 @@ class TLSWrap : public crypto::SSLWrap, // If true - delivered EOF to the js-land, either after `close_notify`, or // after the `UV_EOF` on socket. bool eof_; - -#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB - v8::Persistent<:value> sni_context_; -#endif // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB }; } // namespace node diff --git a/src/util.cc b/src/util.cc index f382b3d565a8cf..a793368c2cdfa8 100644 --- a/src/util.cc +++ b/src/util.cc @@ -13,7 +13,7 @@ Utf8Value::Utf8Value(v8::Isolate* isolate, v8::Handle<:value> value) return; // Allocate enough space to include the null terminator - size_t len = StringBytes::StorageSize(string, UTF8) + 1; + size_t len = StringBytes::StorageSize(isolate, string, UTF8) + 1; if (len > sizeof(str_st_)) { str_ = static_cast(malloc(len)); CHECK_NE(str_, nullptr); diff --git a/test/.eslintrc b/test/.eslintrc new file mode 100644 index 00000000000000..d5d95584ea6811 --- /dev/null +++ b/test/.eslintrc @@ -0,0 +1,5 @@ +## Test-specific linter rules + +rules: + ## allow unreachable code + no-unreachable: 0 diff --git a/test/addons/async-hello-world/test.js b/test/addons/async-hello-world/test.js index 83f5e7206ec073..a284a019f01a8b 100644 --- a/test/addons/async-hello-world/test.js +++ b/test/addons/async-hello-world/test.js @@ -1,15 +1,16 @@ +'use strict'; var assert = require('assert'); var binding = require('./build/Release/binding'); var called = false; -process.on('exit', function () { +process.on('exit', function() { assert(called); }); -binding(5, function (err, val) { +binding(5, function(err, val) { assert.equal(null, err); assert.equal(10, val); - process.nextTick(function () { + process.nextTick(function() { called = true; }); }); diff --git a/test/addons/at-exit/test.js b/test/addons/at-exit/test.js index 4466b898afe597..c36f59b976e983 100644 --- a/test/addons/at-exit/test.js +++ b/test/addons/at-exit/test.js @@ -1 +1,2 @@ +'use strict'; var binding = require('./build/Release/binding'); diff --git a/test/addons/hello-world-function-export/test.js b/test/addons/hello-world-function-export/test.js index 238e105381dd54..1056386583faf1 100644 --- a/test/addons/hello-world-function-export/test.js +++ b/test/addons/hello-world-function-export/test.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var binding = require('./build/Release/binding'); assert.equal('world', binding()); diff --git a/test/addons/hello-world/test.js b/test/addons/hello-world/test.js index 18008db58124b2..c0492292fd7250 100644 --- a/test/addons/hello-world/test.js +++ b/test/addons/hello-world/test.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var binding = require('./build/Release/binding'); assert.equal('world', binding.hello()); diff --git a/test/addons/repl-domain-abort/test.js b/test/addons/repl-domain-abort/test.js index f0d968d173f005..a520df03805ccb 100644 --- a/test/addons/repl-domain-abort/test.js +++ b/test/addons/repl-domain-abort/test.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var repl = require('repl'); var stream = require('stream'); diff --git a/test/addons/smalloc-alloc/test.js b/test/addons/smalloc-alloc/test.js index 47197be631ed17..76648e04c4ce07 100644 --- a/test/addons/smalloc-alloc/test.js +++ b/test/addons/smalloc-alloc/test.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var binding = require('./build/Release/binding'); var obj = binding.alloc(16); diff --git a/test/common.js b/test/common.js index ec0b387328d6b7..94d6f2109576b9 100644 --- a/test/common.js +++ b/test/common.js @@ -1,3 +1,4 @@ +'use strict'; var path = require('path'); var fs = require('fs'); var assert = require('assert'); @@ -107,8 +108,8 @@ if (process.env.NODE_COMMON_PIPE) { if (process.platform === 'win32') { exports.faketimeCli = false; } else { - exports.faketimeCli = path.join(__dirname, "..", "tools", "faketime", "src", - "faketime"); + exports.faketimeCli = path.join(__dirname, '..', 'tools', 'faketime', 'src', + 'faketime'); } var ifaces = os.networkInterfaces(); @@ -307,7 +308,7 @@ exports.mustCall = function(fn, expected) { var context = { expected: expected, actual: 0, - stack: (new Error).stack, + stack: (new Error()).stack, name: fn.name || '' }; @@ -345,11 +346,11 @@ if (process.platform === 'win32') { */ exports.getServiceName = function getServiceName(port, protocol) { if (port == null) { - throw new Error("Missing port number"); + throw new Error('Missing port number'); } if (typeof protocol !== 'string') { - throw new Error("Protocol must be a string"); + throw new Error('Protocol must be a string'); } /* @@ -360,10 +361,10 @@ exports.getServiceName = function getServiceName(port, protocol) { try { /* - * I'm not a big fan of readFileSync, but reading /etc/services asynchronously - * here would require implementing a simple line parser, which seems overkill - * for a simple utility function that is not running concurrently with any - * other one. + * I'm not a big fan of readFileSync, but reading /etc/services + * asynchronously here would require implementing a simple line parser, + * which seems overkill for a simple utility function that is not running + * concurrently with any other one. */ var servicesContent = fs.readFileSync(etcServicesFileName, { encoding: 'utf8'}); @@ -380,7 +381,7 @@ exports.getServiceName = function getServiceName(port, protocol) { } return serviceName; -} +}; exports.hasMultiLocalhost = function hasMultiLocalhost() { var TCP = process.binding('tcp_wrap').TCP; @@ -397,7 +398,7 @@ exports.isValidHostname = function(str) { '(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$'); return !!str.match(re) && str.length <= 255; -} +}; exports.fileExists = function(pathname) { try { diff --git a/test/debugger/helper-debugger-repl.js b/test/debugger/helper-debugger-repl.js index c3f219874e43af..714a22c2a22fdc 100644 --- a/test/debugger/helper-debugger-repl.js +++ b/test/debugger/helper-debugger-repl.js @@ -1,3 +1,4 @@ +'use strict'; process.env.NODE_DEBUGGER_TIMEOUT = 2000; var common = require('../common'); var assert = require('assert'); @@ -55,7 +56,7 @@ function startDebugger(scriptToDebug) { quitCalled = true; child.stdin.write('quit'); child.kill('SIGTERM'); - } + }; setTimeout(function() { console.error('dying badly buffer=%j', buffer); diff --git a/test/debugger/test-debug-break-on-uncaught.js b/test/debugger/test-debug-break-on-uncaught.js index 57095d93abf9a0..397c4225d27f7e 100644 --- a/test/debugger/test-debug-break-on-uncaught.js +++ b/test/debugger/test-debug-break-on-uncaught.js @@ -1,3 +1,4 @@ +'use strict'; var path = require('path'); var assert = require('assert'); var spawn = require('child_process').spawn; @@ -44,7 +45,7 @@ function runScenario(scriptName, throwsInFile, throwsOnLine, next) { child.on('close', function() { assert(asserted, 'debugger did not pause on exception'); if (next) next(); - }) + }); var exceptions = []; diff --git a/test/debugger/test-debugger-client.js b/test/debugger/test-debugger-client.js index 4bb27c277eab72..972c94707ee56b 100644 --- a/test/debugger/test-debugger-client.js +++ b/test/debugger/test-debugger-client.js @@ -1,3 +1,4 @@ +'use strict'; process.env.NODE_DEBUGGER_TIMEOUT = 2000; var common = require('../common'); var assert = require('assert'); @@ -66,7 +67,7 @@ var d = 'Content-Length: 466\r\n\r\n' + '{"seq":10,"type":"event","event":"afterCompile","success":true,' + '"body":{"script":{"handle":1,"type":"script","name":"dns.js",' + '"id":34,"lineOffset":0,"columnOffset":0,"lineCount":241,' + - '"sourceStart":"(function (module, exports, require) {' + + '"sourceStart":"(function(module, exports, require) {' + 'var dns = process.binding(\'cares\')' + ';\\nvar ne","sourceLength":6137,"scriptType":2,"compilationType":0,' + '"context":{"ref":0},"text":"dns.js (lines: 241)"}},"refs":' + @@ -127,8 +128,8 @@ addTest(function(client, done) { var connectCount = 0; -var script = 'setTimeout(function () { console.log("blah"); });' + - 'setInterval(function () {}, 1000000);'; +var script = 'setTimeout(function() { console.log("blah"); });' + + 'setInterval(function() {}, 1000000);'; var nodeProcess; diff --git a/test/debugger/test-debugger-debug-brk.js b/test/debugger/test-debugger-debug-brk.js index 7bf7d639f5362c..3b54f853bc8de3 100644 --- a/test/debugger/test-debugger-debug-brk.js +++ b/test/debugger/test-debugger-debug-brk.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/debugger/test-debugger-remote.js b/test/debugger/test-debugger-remote.js index 641199a1714af7..abb67c19cbf0cd 100644 --- a/test/debugger/test-debugger-remote.js +++ b/test/debugger/test-debugger-remote.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/debugger/test-debugger-repl-break-in-module.js b/test/debugger/test-debugger-repl-break-in-module.js index 8d33d126438064..995f6fe0db3a3d 100644 --- a/test/debugger/test-debugger-repl-break-in-module.js +++ b/test/debugger/test-debugger-repl-break-in-module.js @@ -1,3 +1,4 @@ +'use strict'; var repl = require('./helper-debugger-repl.js'); repl.startDebugger('break-in-module/main.js'); diff --git a/test/debugger/test-debugger-repl-restart.js b/test/debugger/test-debugger-repl-restart.js index 9d83d67188a63c..d3b2c169dea0a8 100644 --- a/test/debugger/test-debugger-repl-restart.js +++ b/test/debugger/test-debugger-repl-restart.js @@ -1,3 +1,4 @@ +'use strict'; var repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); @@ -7,7 +8,7 @@ var linesWithBreakpoint = [ // We slice here, because addTest will change the given array. repl.addTest('sb(6)', linesWithBreakpoint.slice()); -var initialLines = repl.initialLines.slice() +var initialLines = repl.initialLines.slice(); initialLines.splice(2, 0, /Restoring/, /Warning/); // Restart the debugged script diff --git a/test/debugger/test-debugger-repl-term.js b/test/debugger/test-debugger-repl-term.js index a42a253c5a9aee..741adf682ab1dd 100644 --- a/test/debugger/test-debugger-repl-term.js +++ b/test/debugger/test-debugger-repl-term.js @@ -1,3 +1,4 @@ +'use strict'; process.env.NODE_FORCE_READLINE = 1; var repl = require('./helper-debugger-repl.js'); diff --git a/test/debugger/test-debugger-repl-utf8.js b/test/debugger/test-debugger-repl-utf8.js index 0fccf2477b03ab..c32216e5d6dc66 100644 --- a/test/debugger/test-debugger-repl-utf8.js +++ b/test/debugger/test-debugger-repl-utf8.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var script = common.fixturesDir + '/breakpoints_utf8.js'; process.env.NODE_DEBUGGER_TEST_SCRIPT = script; diff --git a/test/debugger/test-debugger-repl.js b/test/debugger/test-debugger-repl.js index 788ea9cb6a273f..2e44da55d72859 100644 --- a/test/debugger/test-debugger-repl.js +++ b/test/debugger/test-debugger-repl.js @@ -1,3 +1,4 @@ +'use strict'; var repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); diff --git a/test/disabled/GH-670.js b/test/disabled/GH-670.js index af65bbdc0ffc95..28f90a72ad487a 100644 --- a/test/disabled/GH-670.js +++ b/test/disabled/GH-670.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var https = require('https'); diff --git a/test/disabled/test-cat.js b/test/disabled/test-cat.js index 02d2d41a6663c8..e37820ba4b338c 100644 --- a/test/disabled/test-cat.js +++ b/test/disabled/test-cat.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common.js'); var assert = require('assert'); var http = require('http'); diff --git a/test/disabled/test-child-process-custom-fds.js b/test/disabled/test-child-process-custom-fds.js index d64586c508d9f1..12087684727dbf 100644 --- a/test/disabled/test-child-process-custom-fds.js +++ b/test/disabled/test-child-process-custom-fds.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-child-process-customfd-bounded.js b/test/disabled/test-child-process-customfd-bounded.js index 203e6acaf379c5..98da4ef4d1391e 100644 --- a/test/disabled/test-child-process-customfd-bounded.js +++ b/test/disabled/test-child-process-customfd-bounded.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var bigish = Array(200); diff --git a/test/disabled/test-child-process-uid-gid.js b/test/disabled/test-child-process-uid-gid.js index 5ab570b813f48f..90708bc2ca4016 100644 --- a/test/disabled/test-child-process-uid-gid.js +++ b/test/disabled/test-child-process-uid-gid.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/disabled/test-debug-brk-file.js b/test/disabled/test-debug-brk-file.js index ca2af1b7121811..4b5823f56a64e1 100644 --- a/test/disabled/test-debug-brk-file.js +++ b/test/disabled/test-debug-brk-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/disabled/test-debug-brk-no-arg.js b/test/disabled/test-debug-brk-no-arg.js index 547cd1b287a9ed..7e678a76dfc8f8 100644 --- a/test/disabled/test-debug-brk-no-arg.js +++ b/test/disabled/test-debug-brk-no-arg.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/disabled/test-dgram-multicast.js b/test/disabled/test-dgram-multicast.js index d66bd63e50dcbe..f2668d24c9a51a 100644 --- a/test/disabled/test-dgram-multicast.js +++ b/test/disabled/test-dgram-multicast.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-dgram-send-error.js b/test/disabled/test-dgram-send-error.js index 00901dd563f7d8..1ed594a389a8c4 100644 --- a/test/disabled/test-dgram-send-error.js +++ b/test/disabled/test-dgram-send-error.js @@ -1,3 +1,4 @@ +'use strict'; // Some operating systems report errors when an UDP message is sent to an // unreachable host. This error can be reported by sendto() and even by // recvfrom(). Node should not propagate this error to the user. diff --git a/test/disabled/test-dgram-unix-anon.js b/test/disabled/test-dgram-unix-anon.js index 1a8b5e3a57bd73..417ff8c2915f32 100644 --- a/test/disabled/test-dgram-unix-anon.js +++ b/test/disabled/test-dgram-unix-anon.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-dgram-unix.js b/test/disabled/test-dgram-unix.js index f2a24a9c361c8e..d8ebd81a92da9d 100644 --- a/test/disabled/test-dgram-unix.js +++ b/test/disabled/test-dgram-unix.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-eio-race.js b/test/disabled/test-eio-race.js index b9e14f76b22f5d..32585894d0d7c3 100644 --- a/test/disabled/test-eio-race.js +++ b/test/disabled/test-eio-race.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -36,7 +37,7 @@ function tryToKillEventLoop() { // Generate a lot of thread pool events var pos = 0; -fs.open(filename, 'r', 0666, function(err, fd) { +fs.open(filename, 'r', 0o666, function(err, fd) { if (err) throw err; function readChunk() { diff --git a/test/disabled/test-eio-race2.js b/test/disabled/test-eio-race2.js index 487486a15d8245..16c0468775adf8 100644 --- a/test/disabled/test-eio-race2.js +++ b/test/disabled/test-eio-race2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/disabled/test-eio-race3.js b/test/disabled/test-eio-race3.js index 820128ae463fcd..872a105dd5ac90 100644 --- a/test/disabled/test-eio-race3.js +++ b/test/disabled/test-eio-race3.js @@ -1,3 +1,4 @@ +'use strict'; /* XXX Can this test be modified to not call the now-removed wait()? */ var common = require('../common'); diff --git a/test/disabled/test-eio-race4.js b/test/disabled/test-eio-race4.js index e8a2e591362d83..d22c4225b1544e 100644 --- a/test/disabled/test-eio-race4.js +++ b/test/disabled/test-eio-race4.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/disabled/test-fs-largefile.js b/test/disabled/test-fs-largefile.js index 21406e3aad0431..498bfa45a06dda 100644 --- a/test/disabled/test-fs-largefile.js +++ b/test/disabled/test-fs-largefile.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'), diff --git a/test/disabled/test-http-abort-stream-end.js b/test/disabled/test-http-abort-stream-end.js index b0a23d92defe26..cfa531cedf5523 100644 --- a/test/disabled/test-http-abort-stream-end.js +++ b/test/disabled/test-http-abort-stream-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-http-agent2.js b/test/disabled/test-http-agent2.js index c1ccd70a1e4fd4..928194757b3a5d 100644 --- a/test/disabled/test-http-agent2.js +++ b/test/disabled/test-http-agent2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/disabled/test-http-big-proxy-responses.js b/test/disabled/test-http-big-proxy-responses.js index fe70473f587a30..9727edbb80639f 100644 --- a/test/disabled/test-http-big-proxy-responses.js +++ b/test/disabled/test-http-big-proxy-responses.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'), diff --git a/test/disabled/test-http-head-request.js b/test/disabled/test-http-head-request.js index 2dfe20bc3d06d8..c6fa78fe2b7309 100644 --- a/test/disabled/test-http-head-request.js +++ b/test/disabled/test-http-head-request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-http-stress.js b/test/disabled/test-http-stress.js index 09a0b7e48a9e47..e4b51e07ca31df 100644 --- a/test/disabled/test-http-stress.js +++ b/test/disabled/test-http-stress.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-http-tls.js b/test/disabled/test-http-tls.js index 384849d00df140..867c3a076aefdc 100644 --- a/test/disabled/test-http-tls.js +++ b/test/disabled/test-http-tls.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-https-loop-to-google.js b/test/disabled/test-https-loop-to-google.js index cb29f2c226fb14..e498895ed23be0 100644 --- a/test/disabled/test-https-loop-to-google.js +++ b/test/disabled/test-https-loop-to-google.js @@ -1,3 +1,4 @@ +'use strict'; // Failing test for https // Will fail with "socket hang up" for 4 out of 10 requests @@ -7,26 +8,20 @@ var common = require('../common'); var https = require('https'); -for (var i = 0; i < 10; ++i) -{ - https.get( - { - host: 'www.google.com', - path: '/accounts/o8/id', - port: 443 - }, function(res) - { - var data = ''; - res.on('data', function(chunk) - { - data += chunk; - }); - res.on('end', function() - { - console.log(res.statusCode); - }); - }).on('error', function(error) - { - console.log(error); - }); +for (var i = 0; i < 10; ++i) { + https.get({ + host: 'www.google.com', + path: '/accounts/o8/id', + port: 443 + }, function(res) { + var data = ''; + res.on('data', function(chunk) { + data += chunk; + }); + res.on('end', function() { + console.log(res.statusCode); + }); + }).on('error', function(error) { + console.log(error); + }); } diff --git a/test/disabled/test-idle-watcher.js b/test/disabled/test-idle-watcher.js index b1038d56fd1b9e..6cf78ad1740953 100644 --- a/test/disabled/test-idle-watcher.js +++ b/test/disabled/test-idle-watcher.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-net-fd-passing.js b/test/disabled/test-net-fd-passing.js index 7b73056393ec3f..380032a2e66b5b 100644 --- a/test/disabled/test-net-fd-passing.js +++ b/test/disabled/test-net-fd-passing.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/disabled/test-net-tls-pummel.js b/test/disabled/test-net-tls-pummel.js index 0312d70ea722cb..0fb63d33f441fe 100644 --- a/test/disabled/test-net-tls-pummel.js +++ b/test/disabled/test-net-tls-pummel.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-net-tls.js b/test/disabled/test-net-tls.js index 9783b7ee3c81a1..01797fc689f44f 100644 --- a/test/disabled/test-net-tls.js +++ b/test/disabled/test-net-tls.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/disabled/test-process-title.js b/test/disabled/test-process-title.js index 1cd361dd87c572..629d78d72373a7 100644 --- a/test/disabled/test-process-title.js +++ b/test/disabled/test-process-title.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/disabled/test-readline.js b/test/disabled/test-readline.js index 1572036a8749d9..9bb9943bd2a403 100644 --- a/test/disabled/test-readline.js +++ b/test/disabled/test-readline.js @@ -1,3 +1,4 @@ +'use strict'; // Can't test this when 'make test' doesn't assign a tty to the stdout. // Yet another use-case for require('tty').spawn ? var common = require('../common'); @@ -36,10 +37,10 @@ var readlineFakeStream = function() { } }); var _stdoutWrite = process.stdout.write; - process.stdout.write = function (data) { + process.stdout.write = function(data) { data.split('').forEach(rl.written_bytes.push.bind(rl.written_bytes)); _stdoutWrite.apply(this, arguments); - } + }; rl.written_bytes = written_bytes; return rl; }; @@ -49,7 +50,7 @@ var written_bytes_length, refreshed; rl.write('foo'); assert.equal(3, rl.cursor); -[key.xterm, key.rxvt, key.gnome, key.putty].forEach(function (key) { +[key.xterm, key.rxvt, key.gnome, key.putty].forEach(function(key) { rl.write.apply(rl, key.home); assert.equal(0, rl.cursor); rl.write.apply(rl, key.end); @@ -72,7 +73,7 @@ rl.write.apply(rl, key.xterm.home); {cursor: 7, key: key.xterm.metab}, {cursor: 4, key: key.xterm.metab}, {cursor: 0, key: key.xterm.metab}, -].forEach(function (action) { +].forEach(function(action) { written_bytes_length = rl.written_bytes.length; rl.write.apply(rl, action.key); assert.equal(action.cursor, rl.cursor); @@ -83,7 +84,14 @@ rl.write.apply(rl, key.xterm.home); rl = readlineFakeStream(); rl.write('foo bar.hop/zoo'); rl.write.apply(rl, key.xterm.home); -['bar.hop/zoo', '.hop/zoo', 'hop/zoo', '/zoo', 'zoo', ''].forEach(function (expectedLine) { +[ + 'bar.hop/zoo', + '.hop/zoo', + 'hop/zoo', + '/zoo', + 'zoo', + '' +].forEach(function(expectedLine) { rl.write.apply(rl, key.xterm.metad); assert.equal(0, rl.cursor); assert.equal(expectedLine, rl.line); diff --git a/test/disabled/test-remote-module-loading.js b/test/disabled/test-remote-module-loading.js index c4d90fb80d0c50..d589ecf35be4b7 100644 --- a/test/disabled/test-remote-module-loading.js +++ b/test/disabled/test-remote-module-loading.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-sendfd.js b/test/disabled/test-sendfd.js index 0e1dd6f1bff37a..4eefbeab549685 100644 --- a/test/disabled/test-sendfd.js +++ b/test/disabled/test-sendfd.js @@ -1,3 +1,4 @@ +'use strict'; // Test sending and receiving a file descriptor. // // This test is pretty complex. It ends up spawning test/fixtures/recvfd.js diff --git a/test/disabled/test-setuidgid.js b/test/disabled/test-setuidgid.js index 90923b922d7711..bf3726ab006d36 100644 --- a/test/disabled/test-setuidgid.js +++ b/test/disabled/test-setuidgid.js @@ -1,3 +1,4 @@ +'use strict'; // Requires special privileges var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-tls-large-push.js b/test/disabled/test-tls-large-push.js index a5e206e477bef2..80a3cf52209a2f 100644 --- a/test/disabled/test-tls-large-push.js +++ b/test/disabled/test-tls-large-push.js @@ -1,3 +1,5 @@ +/* eslint-disable no-debugger */ +'use strict'; // Server sends a large string. Client counts bytes and pauses every few // seconds. Makes sure that pause and resume work properly. var common = require('../common'); @@ -39,7 +41,7 @@ server.listen(common.PORT, function() { /* client.pause(); - process.nextTick(function () { + process.nextTick(function() { client.resume(); }); */ diff --git a/test/disabled/test-tls-server.js b/test/disabled/test-tls-server.js index 20cc3f9fc79c39..c1e62bf01cea20 100644 --- a/test/disabled/test-tls-server.js +++ b/test/disabled/test-tls-server.js @@ -1,3 +1,4 @@ +'use strict'; // Example of new TLS API. Test with: // // $> openssl s_client -connect localhost:12346 \ diff --git a/test/disabled/test-tty-stdio.js b/test/disabled/test-tty-stdio.js index 0d963958abb5bd..57d7ee67759d5a 100644 --- a/test/disabled/test-tty-stdio.js +++ b/test/disabled/test-tty-stdio.js @@ -1,3 +1,4 @@ +'use strict'; // Can't test this when 'make test' doesn't assign a tty to the stdout. var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/tls-client.js b/test/disabled/tls-client.js index 48c715b29baf47..b47b681f95d026 100644 --- a/test/disabled/tls-client.js +++ b/test/disabled/tls-client.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var tls = require('tls'); var fs = require('fs'); diff --git a/test/disabled/tls_client.js b/test/disabled/tls_client.js index 65d18dd7f21256..425cb54a5910fd 100644 --- a/test/disabled/tls_client.js +++ b/test/disabled/tls_client.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/tls_server.js b/test/disabled/tls_server.js index 1174b8f6d04fcc..b3f43b564d067a 100644 --- a/test/disabled/tls_server.js +++ b/test/disabled/tls_server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/fixtures/child-process-persistent.js b/test/fixtures/child-process-persistent.js index 226ab3329d91d4..45a50f5a263ad6 100644 --- a/test/fixtures/child-process-persistent.js +++ b/test/fixtures/child-process-persistent.js @@ -1 +1 @@ -setInterval(function () {}, 500); +setInterval(function() {}, 500); diff --git a/test/fixtures/keys/Makefile b/test/fixtures/keys/Makefile index a096431a8c3307..1e3d40ebf1f91a 100644 --- a/test/fixtures/keys/Makefile +++ b/test/fixtures/keys/Makefile @@ -17,6 +17,28 @@ ca2-cert.pem: ca2.cnf echo '01' > ca2-serial touch ca2-database.txt +# +# Create Subordinate Certificate Authority: ca3 +# ('password' is used for the CA password.) +# +ca3-key.pem: + openssl genrsa -out ca3-key.pem 1024 + +ca3-csr.pem: ca3.cnf ca3-key.pem + openssl req -new \ + -extensions v3_ca -config ca3.cnf -key ca3-key.pem -out ca3-csr.pem + +ca3-cert.pem: ca3-csr.pem ca3-key.pem ca3.cnf ca1-cert.pem ca1-key.pem + openssl x509 -req \ + -extfile ca3.cnf \ + -extensions v3_ca \ + -days 9999 \ + -passin "pass:password" \ + -in ca3-csr.pem \ + -CA ca1-cert.pem \ + -CAkey ca1-key.pem \ + -CAcreateserial \ + -out ca3-cert.pem # # agent1 is signed by ca1. @@ -157,6 +179,31 @@ agent5-cert.pem: agent5-csr.pem ca2-cert.pem ca2-key.pem agent5-verify: agent5-cert.pem ca2-cert.pem openssl verify -CAfile ca2-cert.pem agent5-cert.pem +# +# agent6 is signed by ca3 +# + +agent6-key.pem: + openssl genrsa -out agent6-key.pem 1024 + +agent6-csr.pem: agent6.cnf agent6-key.pem + openssl req -new -config agent6.cnf -key agent6-key.pem -out agent6-csr.pem + +agent6-cert.pem: agent6-csr.pem ca3-cert.pem ca3-key.pem + openssl x509 -req \ + -days 9999 \ + -passin "pass:password" \ + -in agent6-csr.pem \ + -CA ca3-cert.pem \ + -CAkey ca3-key.pem \ + -CAcreateserial \ + -extfile agent6.cnf \ + -out agent6-cert.pem + cat ca3-cert.pem >> agent6-cert.pem + +agent6-verify: agent6-cert.pem ca3-cert.pem + openssl verify -CAfile ca3-cert.pem agent6-cert.pem + ec-key.pem: openssl ecparam -genkey -out ec-key.pem -name prime256v1 diff --git a/test/fixtures/keys/agent1-cert.pem b/test/fixtures/keys/agent1-cert.pem index c5bfb18e089e85..9c5c2ca4c62ed2 100644 --- a/test/fixtures/keys/agent1-cert.pem +++ b/test/fixtures/keys/agent1-cert.pem @@ -1,9 +1,9 @@ -----BEGIN CERTIFICATE----- -MIIC1jCCAj+gAwIBAgIJAJqEq8+4pyq+MA0GCSqGSIb3DQEBBQUAMHoxCzAJBgNV -BAYTAlVTMQswCQYDVQQIEwJDQTELMAkGA1UEBxMCU0YxDzANBgNVBAoTBkpveWVu -dDEQMA4GA1UECxMHTm9kZS5qczEMMAoGA1UEAxMDY2ExMSAwHgYJKoZIhvcNAQkB -FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xNDA0MTUyMTMxMzFaFw00MTA4MzAyMTMx -MzFaMH0xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTELMAkGA1UEBxMCU0YxDzAN +MIIC1jCCAj+gAwIBAgIJAJqEq8+4pyrAMA0GCSqGSIb3DQEBCwUAMHoxCzAJBgNV +BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzANBgNVBAoMBkpveWVu +dDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2ExMSAwHgYJKoZIhvcNAQkB +FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xNTA0MTgxMzI5MDhaFw00MjA5MDIxMzI5 +MDhaMH0xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTELMAkGA1UEBxMCU0YxDzAN BgNVBAoTBkpveWVudDEQMA4GA1UECxMHTm9kZS5qczEPMA0GA1UEAxMGYWdlbnQx MSAwHgYJKoZIhvcNAQkBFhFyeUB0aW55Y2xvdWRzLm9yZzCBnzANBgkqhkiG9w0B AQEFAAOBjQAwgYkCgYEAuOs3hW8rF+7xx5iB9wjmIgd+HTqRFUeKxG+mWV35Hl6A @@ -11,8 +11,8 @@ AQEFAAOBjQAwgYkCgYEAuOs3hW8rF+7xx5iB9wjmIgd+HTqRFUeKxG+mWV35Hl6A lRxqJGXTjx+vG/0nDCXLBhoDKO00zEccdjGS8xEjjieQQr+KeASmIm0kQmuN5YcC AwEAAaNhMF8wXQYIKwYBBQUHAQEEUTBPMCMGCCsGAQUFBzABhhdodHRwOi8vb2Nz cC5ub2RlanMub3JnLzAoBggrBgEFBQcwAoYcaHR0cDovL2NhLm5vZGVqcy5vcmcv -Y2EuY2VydDANBgkqhkiG9w0BAQUFAAOBgQAx6rhnYbPygJwIm6nidyx+ydJQC4Gk -JD+pzbdJkTS+01r+xjVY/Wckn4JAsIlo/MMn055rs2cfdjoQtlj6yjEU6AP/7bfr -Mju4lBxDLACJ2y5/rfj3wO4q4Knd4Q4mPWjlS2SwmkHZ21QOqJ6Ig9ps6HPM7syw -ZYQ3WQ1LOPAxMg== +Y2EuY2VydDANBgkqhkiG9w0BAQsFAAOBgQA45MmH28Gns+1yu9w9MR/oR8hKDMnG +E4yDZ+9SofWdqRsGe5MNeMbp9c+FxIxODcNmdhV5Ao6+ZCRX4N9GjLqUL1jQoFAs +pT/U80ZU+4bz2EwGMBQt7CJZb/u+j8/vXheyGFZkCWEQj6AgZQFTniRRQJLwbiy5 +uDktGqnhvamyrg== -----END CERTIFICATE----- diff --git a/test/fixtures/keys/agent6-cert.pem b/test/fixtures/keys/agent6-cert.pem new file mode 100644 index 00000000000000..b6c03990f4c740 --- /dev/null +++ b/test/fixtures/keys/agent6-cert.pem @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIICajCCAdOgAwIBAgIJAMTNiT75p13MMA0GCSqGSIb3DQEBCwUAMHoxCzAJBgNV +BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzANBgNVBAoMBkpveWVu +dDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2EzMSAwHgYJKoZIhvcNAQkB +FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xNTA0MTgxMzI4NDFaFw00MjA5MDIxMzI4 +NDFaMHQxCzAJBgNVBAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDERMA8GA1UECgwI +VHJlc29yaXQxFjAUBgNVBAMMDcOBZMOhbSBMaXBwYWkxJzAlBgkqhkiG9w0BCQEW +GGFkYW0ubGlwcGFpQHRyZXNvcml0LmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAw +gYkCgYEA3Iwmwd6gdWH1AlSFeuVsEY/2MQm3XluOyHR9HNtXkWqwcQqVL8FX3NHt +//1jaSTMJjkR4FhC9R0hX6wyUuBp11J4GzoDqd02JUkCeUISq/3/2G+ynaZCx5Eo +GNHhcN0gALTCET/1QMD9h4aBjRbij3iHUghcbgverfkasp59WWcCAwEAATANBgkq +hkiG9w0BAQsFAAOBgQAmfrCJY+FPeOraPTUQTYf9rXqfVRQEVc/yyVygPbtg3gtA +yST0wI/g6sBjQ6Mm39yMf4rkWmwOKGtrKcqs9o9NdM5g5QQSWeg925Ex6aB+REgz +qjaAsLM88BJ0QU76VPi6K0hDSpeuQ6Zrcp93VkdGdVZzna3FSCMTNRnSq/GuMQ== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICgjCCAeugAwIBAgIJAJqEq8+4pyq/MA0GCSqGSIb3DQEBCwUAMHoxCzAJBgNV +BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzANBgNVBAoMBkpveWVu +dDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2ExMSAwHgYJKoZIhvcNAQkB +FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xNTA0MTgxMzI4NDFaFw00MjA5MDIxMzI4 +NDFaMHoxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzAN +BgNVBAoMBkpveWVudDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2EzMSAw +HgYJKoZIhvcNAQkBFhFyeUB0aW55Y2xvdWRzLm9yZzCBnzANBgkqhkiG9w0BAQEF +AAOBjQAwgYkCgYEAqs4MKn9saUIu/9EfHQPouC3kL9Mo5sd1WR6RBeSd8cqeFxXW +EWEq/P0hUeAH1sY0u8RFOccJmSJg8KTyRGc+VZzWimopz17mTuQY4hPW4bFzqmQm +7STfJz5eHzynBTU8jk5omi8hjbnRA38jOm4D7rN/vqtB+RG+vEhxONnq4DMCAwEA +AaMQMA4wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOBgQBo8rX1uZWHvKHG +gWw+LXrY24Pkg8NdDRmfqEVyuaR4GoGGOXCqlVaFa6x+4/eqOUzHoC9uGfPtjrvW +BYQ1o/l0JZWW4KZYuXoVuMUSj+sel82mf9zLDeq5WYTPECgJDMfgVpXOmhHfyezn +SkUTX7XJUohjET+X5BqTFlqRT/RfIw== +-----END CERTIFICATE----- diff --git a/test/fixtures/keys/agent6-csr.pem b/test/fixtures/keys/agent6-csr.pem new file mode 100644 index 00000000000000..9d1925682b3903 --- /dev/null +++ b/test/fixtures/keys/agent6-csr.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIB2TCCAUICAQAwdDELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MREw +DwYDVQQKDAhUcmVzb3JpdDEWMBQGA1UEAwwNw4Fkw6FtIExpcHBhaTEnMCUGCSqG +SIb3DQEJARYYYWRhbS5saXBwYWlAdHJlc29yaXQuY29tMIGfMA0GCSqGSIb3DQEB +AQUAA4GNADCBiQKBgQDcjCbB3qB1YfUCVIV65WwRj/YxCbdeW47IdH0c21eRarBx +CpUvwVfc0e3//WNpJMwmORHgWEL1HSFfrDJS4GnXUngbOgOp3TYlSQJ5QhKr/f/Y +b7KdpkLHkSgY0eFw3SAAtMIRP/VAwP2HhoGNFuKPeIdSCFxuC96t+Rqynn1ZZwID +AQABoCUwIwYJKoZIhvcNAQkHMRYMFEEgY2hhbGxlbmdlIHBhc3N3b3JkMA0GCSqG +SIb3DQEBCwUAA4GBAEU4gmRyeeh5TMYG3bI0biXr+9CvkYBaHwZD5o4TUo8AenIR +NTrJdy9Pg9B23eOnEnCDB+KMfl08UuaPxbKRXRtYm1rTC8v5wmJEpZdWxum4c3hL +3o7J8/LmjRGQImr5vnS5zmsVrBLtjW+jVpSg5xnXFKQmpXPfgRwhvbu0lXf7 +-----END CERTIFICATE REQUEST----- diff --git a/test/fixtures/keys/agent6-key.pem b/test/fixtures/keys/agent6-key.pem new file mode 100644 index 00000000000000..e42fa2d1d1bd33 --- /dev/null +++ b/test/fixtures/keys/agent6-key.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXgIBAAKBgQDcjCbB3qB1YfUCVIV65WwRj/YxCbdeW47IdH0c21eRarBxCpUv +wVfc0e3//WNpJMwmORHgWEL1HSFfrDJS4GnXUngbOgOp3TYlSQJ5QhKr/f/Yb7Kd +pkLHkSgY0eFw3SAAtMIRP/VAwP2HhoGNFuKPeIdSCFxuC96t+Rqynn1ZZwIDAQAB +AoGBAIL3AsjbL8OksL56fG0XMY5YQ6SpFWeFzQsCCY2KPrzOcwodc6vRDyDE1KTP +zimQvV3xQ8lKADDX5IqQka2fL5mgF+LighVvGHDm6M4ILJb46SDbuINwnqqvVuye ++OwjHBGEmKu18K+eL/YoCh3+sFTKP/18F7c7DGskCyzyub5RAkEA+Fs1ROx5w8AH +cbIH4fMU/QBGQVnuKgNXGSPcT6NHqFLbrhvNn5HwoF1SiJKkML1h3gVpj3T8kquw +Y1FcTVB9eQJBAONV1qXFo7i5gl2FyPuXvpgdzIXxzzr6q3seDkCR7q/vfBo+kKAx +zyG2xjJrCc9+ox4Vh257qK9b57W6R6sWNd8CQQCeAHjNVpzI2nxh6t908k8h/nCz +1uDcPa/FwLjCuaA3CC/Wfr28jP5HJ9gAJzrp/zIqK8tShxzAuxXGudY9Ib4RAkEA +v+3elIIx4WktOQwUTOUmEoNGAufOD3tGf2E2oykRnRPRcM7Vh4nF2C7ZUgOweq/t +wx5mAs7/8VzkWTb1/ul3fQJACLBXTChgyA77i5C/035tLwQbeLOjexLblEI0dgkW +HIa8q4ZL0M7L+/oziQ8zIT0bTAqEG1Q00PgFLl3m8gDuNg== +-----END RSA PRIVATE KEY----- diff --git a/test/fixtures/keys/agent6.cnf b/test/fixtures/keys/agent6.cnf new file mode 100644 index 00000000000000..1b66c9b0d7bac1 --- /dev/null +++ b/test/fixtures/keys/agent6.cnf @@ -0,0 +1,18 @@ +[ req ] +string_mask = utf8only +utf8 = yes +default_bits = 1024 +days = 999 +distinguished_name = req_distinguished_name +attributes = req_attributes +prompt = no + +[ req_distinguished_name ] +C = HU +L = Budapest +O = Tresorit +CN = Ádám Lippai +emailAddress = [email protected] + +[ req_attributes ] +challengePassword = A challenge password diff --git a/test/fixtures/keys/ca1-cert.pem b/test/fixtures/keys/ca1-cert.pem index 638c803c7fb3fb..8e45f8891c14e0 100644 --- a/test/fixtures/keys/ca1-cert.pem +++ b/test/fixtures/keys/ca1-cert.pem @@ -1,15 +1,16 @@ -----BEGIN CERTIFICATE----- -MIICazCCAdQCCQC1CQyJn8L/kzANBgkqhkiG9w0BAQUFADB6MQswCQYDVQQGEwJV -UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO -BgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMTEgMB4GCSqGSIb3DQEJARYRcnlA -dGlueWNsb3Vkcy5vcmcwHhcNMTQwNDE1MjEzMTMxWhcNNDEwODMwMjEzMTMxWjB6 -MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQK -EwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMTEgMB4GCSqG -SIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwgZ8wDQYJKoZIhvcNAQEBBQADgY0A -MIGJAoGBALBXMk/xFR2GN2v/wKreZKyIitGphxYGoJ2d//s/wM6qqyIW94aiq3sm -1zpmOTPTorT9Pk32A7uKKHfrafB+yA07QXgCYXgzcn17nfFInncDyGdggNFGAO13 -5JuC3JC8pRJpEokkMszpHJxPdR6gKXIT05blUnpwGT/AmYJ8S59lAgMBAAEwDQYJ -KoZIhvcNAQEFBQADgYEAAb+Pye0I+k927Qi2+cUowLS5MtmrEosUbTYwI4rqYSR2 -aiibqmC3Z55N72ktQ2pJKP8I1t3Rk+j8/yIKWzSn5Jd2GT4ZzqbANrdLKeAsfVDK -pnsUR1IV/sdIvuELm+P4kyK5wafJytUjD+A4SH2oWN4EozDR1OidAhJrraXQksw= +MIICgjCCAeugAwIBAgIJAI3yHAFGivOTMA0GCSqGSIb3DQEBCwUAMHoxCzAJBgNV +BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzANBgNVBAoMBkpveWVu +dDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2ExMSAwHgYJKoZIhvcNAQkB +FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xNTA0MTgxMzI4NDFaFw00MjA5MDIxMzI4 +NDFaMHoxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzAN +BgNVBAoMBkpveWVudDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2ExMSAw +HgYJKoZIhvcNAQkBFhFyeUB0aW55Y2xvdWRzLm9yZzCBnzANBgkqhkiG9w0BAQEF +AAOBjQAwgYkCgYEAwbF7gKfk7nGLcH0lbok1UJEBpMiQ49YxUqT/oIfXBaRjMODX +RknQxpARWw4R8qj+Zeu9zZZ8Hzv3dAxtcpnMTgeoPUL3HCStk0bK8QrFdkFrBxQD +mF92r9Mgr/fz+x7rSZuCIKhATwB5iJOz63fRctTL5tBmzG15JUG1GN5HPZECAwEA +AaMQMA4wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOBgQAnAHtchz5FGqod +8twiFF3yQdGN3WE3VC3A6VrcmjKUp+M7f0uRDYw4uKUhadyZdYhMn39fe9DVN6rC +6wUUoe4hSs+0SWi6Ora7DFpCbm6fNpooSr0K0OUMZ2opwDmAEPdVOSPRhzQJ/cNp +s3mxIrkAQ5kgJSSGlPETMEumQmXDfA== -----END CERTIFICATE----- diff --git a/test/fixtures/keys/ca1-cert.srl b/test/fixtures/keys/ca1-cert.srl index ab9c1c224ad882..c9650b0529c100 100644 --- a/test/fixtures/keys/ca1-cert.srl +++ b/test/fixtures/keys/ca1-cert.srl @@ -1 +1 @@ -9A84ABCFB8A72ABE +9A84ABCFB8A72AC0 diff --git a/test/fixtures/keys/ca1-key.pem b/test/fixtures/keys/ca1-key.pem index a253989934ce10..3a619fbf2484ff 100644 --- a/test/fixtures/keys/ca1-key.pem +++ b/test/fixtures/keys/ca1-key.pem @@ -1,17 +1,17 @@ -----BEGIN ENCRYPTED PRIVATE KEY----- -MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIJ36Z9tFiv2oCAggA -MBQGCCqGSIb3DQMHBAjCAyUwdFh+7gSCAoD9Sv9009MmLb8+wHhYhxmrPrpeYZOt -W8xfELfal/2XWFe41WV41Qsa2HyN03VeyQjb+cnKvZX6HUCe5zVMUsf+B91yQBqR -jOZgsgoflEC3tFrhW5ogmRnjuok3CbTYLx0f8GMucSRNa9ZPhpfUjrVcCUrKKRJ+ -owk0VxWQkRqMF/8WJJgHxnm8/jLbNKuHbwY8SSQO/pStyKxqx5rBXAA/YCrAx7EZ -aDvc2q9EwRHX+hWIhpIkYna7PwnNAX03Ghv4iiwUlwHoomvgxExdUc9T8HBQu/xP -2pmUqwTglAdRb0tNiYrF+yIesAlqBc1qoi7tv2SM3gTowdw2PeHq5MA/ShV21oC8 -51bc0OxRkEFsHGLIs1v5qzs21JhX0IKvb5LDHAaze2RwODfnCTcQb8jYaFZNmwpt -ZrHgBQBwOHSvZ9CCqInDDtGBhYRlQIQRGgj9Ju5fruRYycn8vE58OcIfF52dwLKB -7sjTFX0O0b58wpiQSJzbHGbjNlQNRXxdk9v1qfP8vx8rFHLoFSScaZomavp4uijU -yLKVwquzEOVOMP8cC+yRk+zkcb9EE2pE1CqG0Mj6MHH1Lha98kakTIAS/VG59/Mp -EqZoRtJ6n/DzscrRpHIm+170ufLGmivmTeOXcMyHv1pGp35c5VbmUTZCxcE7A/0f -WPLVB3lBPgsvR/4NVx9A6mvXbkp2yngdfbvQgzRDG6pfrE1xeiUAyRCts7dR3Q9/ -dNHIM2wsiO3A/8Up1vrY6d/dcJt7cwjHRkx2eQFbpeE+a4CCNZ7gXFcwHLigBH8G -uTTVZf4HJavjXiYlkY3OFnPuz4KzanJzuqluKeIdJwSEkp9Kra/Id0eO +MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQI4tZeEUDNwLoCAggA +MBQGCCqGSIb3DQMHBAglCttpxF+UrASCAoCOiXoMG1+CJFtRnovzp0wSCeEtieI3 +jntJkCBF+NNUZrbWaQqWO+Id8KjXNFQdUo7lYT0d0w5lf52OHTyswjN0ILCOp/WN +eVMDfgmaJXtaah2l++hDFhcbGsOdRcwM0+yComF02Qxr13ftYnIPzUH4+Ix1i1Tr +6eBGDBJv0eXDZj/dLrploA7/pepKlytRw2stIL99TSICR54UQ7fyZ/oS6NvoQU7U +iBCVsrkjyE6jHJZ6vNe/ZjM8ZdLM9K2inoldpFaavDTh6GwHC6e3e9FJuJk6X30e +s2lhrVLOmxLuFS168iApyA8XvVTg/RG08DvkzUUFv8+HNETH0Qkb5kpJM+pPzwyu +c5et2fX8YuQRc8SdIdd+Z0lZJga1IciEXlsfzGeUtcZKUjBZ5yPTx+1InfcNFDKR +wCU2p0Haj9OCcvSBzU53I57RYXkENMEHQ46/FytGULXHimIoIR/SEbrqbKX0xDmT +rc/4c4vI5+tQPYMjo0rqydLAb5YjWCivrXDVXVHrG0YFsAoJkvTBLXlPiqTcnkea +KACuq7B+ymdVmpjV891OLuN3Yah+HgrvTkMlNexsFWvGpis03UYwpI6bppe4dHtt +rLBlgtyxFLJ9hu/YnkR6HcrjKaW5kGFDX06elAZBdPD/6foghzTb4jw3OK6a4ue0 +PE/zF6d7QWW+w5xKtNO62WWKABi9OtLhdUNVAFyBlaA43zYbnXkyfmv0l7LXPZ9t +Ps+BmG4r/gxO6GmZZ40sRXFjpkj230bTjbN6sUrU3WgOszMy0uFAph+zBUIMZWSP +wqZWmQi8MHQ4+Qm8N5GdXUTXw32eZ60bj82QGPso/NNxzDQsk5wd+bR3 -----END ENCRYPTED PRIVATE KEY----- diff --git a/test/fixtures/keys/ca1.cnf b/test/fixtures/keys/ca1.cnf index ea4312752d303f..afd3066eb9daa8 100644 --- a/test/fixtures/keys/ca1.cnf +++ b/test/fixtures/keys/ca1.cnf @@ -5,6 +5,7 @@ distinguished_name = req_distinguished_name attributes = req_attributes prompt = no output_password = password +x509_extensions = v3_ca [ req_distinguished_name ] C = US @@ -18,3 +19,5 @@ emailAddress = [email protected] [ req_attributes ] challengePassword = A challenge password +[ v3_ca ] +basicConstraints = CA:TRUE diff --git a/test/fixtures/keys/ca3-cert.pem b/test/fixtures/keys/ca3-cert.pem new file mode 100644 index 00000000000000..2c1cec87194426 --- /dev/null +++ b/test/fixtures/keys/ca3-cert.pem @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE----- +MIICgjCCAeugAwIBAgIJAJqEq8+4pyq/MA0GCSqGSIb3DQEBCwUAMHoxCzAJBgNV +BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzANBgNVBAoMBkpveWVu +dDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2ExMSAwHgYJKoZIhvcNAQkB +FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xNTA0MTgxMzI4NDFaFw00MjA5MDIxMzI4 +NDFaMHoxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzAN +BgNVBAoMBkpveWVudDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2EzMSAw +HgYJKoZIhvcNAQkBFhFyeUB0aW55Y2xvdWRzLm9yZzCBnzANBgkqhkiG9w0BAQEF +AAOBjQAwgYkCgYEAqs4MKn9saUIu/9EfHQPouC3kL9Mo5sd1WR6RBeSd8cqeFxXW +EWEq/P0hUeAH1sY0u8RFOccJmSJg8KTyRGc+VZzWimopz17mTuQY4hPW4bFzqmQm +7STfJz5eHzynBTU8jk5omi8hjbnRA38jOm4D7rN/vqtB+RG+vEhxONnq4DMCAwEA +AaMQMA4wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOBgQBo8rX1uZWHvKHG +gWw+LXrY24Pkg8NdDRmfqEVyuaR4GoGGOXCqlVaFa6x+4/eqOUzHoC9uGfPtjrvW +BYQ1o/l0JZWW4KZYuXoVuMUSj+sel82mf9zLDeq5WYTPECgJDMfgVpXOmhHfyezn +SkUTX7XJUohjET+X5BqTFlqRT/RfIw== +-----END CERTIFICATE----- diff --git a/test/fixtures/keys/ca3-cert.srl b/test/fixtures/keys/ca3-cert.srl new file mode 100644 index 00000000000000..ecab7285d692e7 --- /dev/null +++ b/test/fixtures/keys/ca3-cert.srl @@ -0,0 +1 @@ +C4CD893EF9A75DCC diff --git a/test/fixtures/keys/ca3-csr.pem b/test/fixtures/keys/ca3-csr.pem new file mode 100644 index 00000000000000..4daa2302ab249b --- /dev/null +++ b/test/fixtures/keys/ca3-csr.pem @@ -0,0 +1,13 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIB3zCCAUgCAQAwejELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQswCQYDVQQH +DAJTRjEPMA0GA1UECgwGSm95ZW50MRAwDgYDVQQLDAdOb2RlLmpzMQwwCgYDVQQD +DANjYTMxIDAeBgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMIGfMA0GCSqG +SIb3DQEBAQUAA4GNADCBiQKBgQCqzgwqf2xpQi7/0R8dA+i4LeQv0yjmx3VZHpEF +5J3xyp4XFdYRYSr8/SFR4AfWxjS7xEU5xwmZImDwpPJEZz5VnNaKainPXuZO5Bji +E9bhsXOqZCbtJN8nPl4fPKcFNTyOTmiaLyGNudEDfyM6bgPus3++q0H5Eb68SHE4 +2ergMwIDAQABoCUwIwYJKoZIhvcNAQkHMRYMFEEgY2hhbGxlbmdlIHBhc3N3b3Jk +MA0GCSqGSIb3DQEBCwUAA4GBABMaKC7NVVdfoQeKwIy5lYo17mOr4WcWHPNRcoIy +rAHLcAzFOp0RCSZ7ROVRR6O/QIBYapUmPmdYRhKfz1g35xCX3+T28cWXngALV5v0 +XzMYJiew+97/LlNnBwoTRafAorviugdbFgJeMpYHRkG7/zXQsBz+hwgymKZnHW9D +Dl4h +-----END CERTIFICATE REQUEST----- diff --git a/test/fixtures/keys/ca3-key.pem b/test/fixtures/keys/ca3-key.pem new file mode 100644 index 00000000000000..6c2b067abed06d --- /dev/null +++ b/test/fixtures/keys/ca3-key.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXAIBAAKBgQCqzgwqf2xpQi7/0R8dA+i4LeQv0yjmx3VZHpEF5J3xyp4XFdYR +YSr8/SFR4AfWxjS7xEU5xwmZImDwpPJEZz5VnNaKainPXuZO5BjiE9bhsXOqZCbt +JN8nPl4fPKcFNTyOTmiaLyGNudEDfyM6bgPus3++q0H5Eb68SHE42ergMwIDAQAB +AoGBAJkcc5N0/j2s8mynjXh5FJhlqvOkGjol+m+VEvNxaJRiySxwiqCxtdNrJf87 +EEvbCVJ4MoYEgfof8z5E3lerJRgqrhY2RSfiQrSUA89Lw9uYzcx28zhWpwwmuLHY +5gjz+LCDDS5okLsXnl2awHXADEmcx29sZnRS6dGRFcf8F0FhAkEA1c7HrW8Vghu2 +FlRaY6LOuoFNAHM++ugoWrC85/moYevLG8wAJCuSIp/RuWrx1FdJoa7rfhyS649v +cMGN0m1yHwJBAMyC1S1QoqXSdoqN8OrXyHJmaSbWG8IMLcT2FXA8Mk3Tk0zWSjiz +sk/O85NsmUQQnkRgbtSS+w0Kc0OMWXbfl20CQH+igFsNjEZuaoXr90WxhD2cQK57 +HebEvopdJXhJ9nX2P/qpDpCJHiTjSVyp9hFvxjnp5RUU07QhnUIvmY073rsCQFMN +ovNHNvZutVNpd3h372B+NJ/f/d/dQE0nvucYmzk9/ikLMZM7buO4YPTy+n9I3G1a +WEgd9LSEFPFOsxpyjTUCQGn9XTyeSo1EoVuV21DE0Cnx30YsnPKMT1YRS7QgjDPK +RA3fSsvnhtTzT53kfJ/ZurBV+RKbePL1JVqDtGvJVeE= +-----END RSA PRIVATE KEY----- diff --git a/test/fixtures/keys/ca3.cnf b/test/fixtures/keys/ca3.cnf new file mode 100644 index 00000000000000..53855e1419617c --- /dev/null +++ b/test/fixtures/keys/ca3.cnf @@ -0,0 +1,23 @@ +[ req ] +default_bits = 1024 +days = 999 +distinguished_name = req_distinguished_name +attributes = req_attributes +prompt = no +output_password = password +x509_extensions = v3_ca + +[ req_distinguished_name ] +C = US +ST = CA +L = SF +O = Joyent +OU = Node.js +CN = ca3 +emailAddress = [email protected] + +[ req_attributes ] +challengePassword = A challenge password + +[ v3_ca ] +basicConstraints = CA:TRUE diff --git a/test/gc/node_modules/weak/lib/weak.js b/test/gc/node_modules/weak/lib/weak.js index 8081a76c45f9f1..535caf615c648e 100644 --- a/test/gc/node_modules/weak/lib/weak.js +++ b/test/gc/node_modules/weak/lib/weak.js @@ -1,3 +1,4 @@ +'use strict'; var bindings try { bindings = require('../build/Release/weakref.node') @@ -13,6 +14,6 @@ module.exports = bindings.create // backwards-compat with node-weakref bindings.weaken = bindings.create -Object.keys(bindings).forEach(function (name) { +Object.keys(bindings).forEach(function(name) { module.exports[name] = bindings[name] }) diff --git a/test/gc/test-http-client-connaborted.js b/test/gc/test-http-client-connaborted.js index c58b4d5f752457..20a4b38481ae0c 100644 --- a/test/gc/test-http-client-connaborted.js +++ b/test/gc/test-http-client-connaborted.js @@ -1,3 +1,4 @@ +'use strict'; // just like test/gc/http-client.js, // but aborting every connection that comes in. @@ -15,7 +16,7 @@ var http = require('http'), assert = require('assert'), PORT = common.PORT; -console.log('We should do '+ todo +' requests'); +console.log('We should do ' + todo + ' requests'); var http = require('http'); var server = http.createServer(serverHandler); @@ -25,9 +26,9 @@ function getall() { if (count >= todo) return; - (function(){ + (function() { function cb(res) { - done+=1; + done += 1; statusLater(); } @@ -39,7 +40,7 @@ function getall() { count++; weak(req, afterGC); - })() + })(); setImmediate(getall); } @@ -47,7 +48,7 @@ function getall() { for (var i = 0; i < 10; i++) getall(); -function afterGC(){ +function afterGC() { countGC ++; } diff --git a/test/gc/test-http-client-onerror.js b/test/gc/test-http-client-onerror.js index bf9fb7c1fba9f8..98d046e180f11b 100644 --- a/test/gc/test-http-client-onerror.js +++ b/test/gc/test-http-client-onerror.js @@ -1,3 +1,4 @@ +'use strict'; // just like test/gc/http-client.js, // but with an on('error') handler that does nothing. @@ -17,7 +18,7 @@ var http = require('http'), assert = require('assert'), PORT = common.PORT; -console.log('We should do '+ todo +' requests'); +console.log('We should do ' + todo + ' requests'); var http = require('http'); var server = http.createServer(serverHandler); @@ -27,10 +28,10 @@ function getall() { if (count >= todo) return; - (function(){ + (function() { function cb(res) { res.resume(); - done+=1; + done += 1; statusLater(); } function onerror(er) { @@ -45,7 +46,7 @@ function getall() { count++; weak(req, afterGC); - })() + })(); setImmediate(getall); } @@ -53,7 +54,7 @@ function getall() { for (var i = 0; i < 10; i++) getall(); -function afterGC(){ +function afterGC() { countGC ++; } diff --git a/test/gc/test-http-client-timeout.js b/test/gc/test-http-client-timeout.js index 727d133f711ad8..5bb2d2b05b4fb0 100644 --- a/test/gc/test-http-client-timeout.js +++ b/test/gc/test-http-client-timeout.js @@ -1,10 +1,11 @@ +'use strict'; // just like test/gc/http-client.js, // but with a timeout set function serverHandler(req, res) { - setTimeout(function () { + setTimeout(function() { req.resume(); - res.writeHead(200) + res.writeHead(200); res.end('hello\n'); }, 100); } @@ -19,7 +20,7 @@ var http = require('http'), assert = require('assert'), PORT = common.PORT; -console.log('We should do '+ todo +' requests'); +console.log('We should do ' + todo + ' requests'); var http = require('http'); var server = http.createServer(serverHandler); @@ -29,10 +30,10 @@ function getall() { if (count >= todo) return; - (function(){ + (function() { function cb(res) { res.resume(); - done+=1; + done += 1; statusLater(); } @@ -42,13 +43,13 @@ function getall() { port: PORT }, cb); req.on('error', cb); - req.setTimeout(10, function(){ - console.log('timeout (expected)') + req.setTimeout(10, function() { + console.log('timeout (expected)'); }); count++; weak(req, afterGC); - })() + })(); setImmediate(getall); } @@ -56,7 +57,7 @@ function getall() { for(var i = 0; i < 10; i++) getall(); -function afterGC(){ +function afterGC() { countGC ++; } diff --git a/test/gc/test-http-client.js b/test/gc/test-http-client.js index 6aedda7edef755..7c3259d38b0ba1 100644 --- a/test/gc/test-http-client.js +++ b/test/gc/test-http-client.js @@ -1,3 +1,4 @@ +'use strict'; // just a simple http server and client. function serverHandler(req, res) { @@ -15,7 +16,7 @@ var http = require('http'), assert = require('assert'), PORT = common.PORT; -console.log('We should do '+ todo +' requests'); +console.log('We should do ' + todo + ' requests'); var http = require('http'); var server = http.createServer(serverHandler); @@ -26,11 +27,11 @@ function getall() { if (count >= todo) return; - (function(){ + (function() { function cb(res) { res.resume(); - console.error('in cb') - done+=1; + console.error('in cb'); + done += 1; res.on('end', gc); } @@ -38,11 +39,11 @@ function getall() { hostname: 'localhost', pathname: '/', port: PORT - }, cb) + }, cb); count++; weak(req, afterGC); - })() + })(); setImmediate(getall); } @@ -50,7 +51,7 @@ function getall() { for (var i = 0; i < 10; i++) getall(); -function afterGC(){ +function afterGC() { countGC ++; } diff --git a/test/gc/test-net-timeout.js b/test/gc/test-net-timeout.js index 2ef03b2632d045..6c3b4f245be452 100644 --- a/test/gc/test-net-timeout.js +++ b/test/gc/test-net-timeout.js @@ -1,3 +1,4 @@ +'use strict'; // just like test/gc/http-client-timeout.js, // but using a net server/client instead @@ -11,7 +12,7 @@ function serverHandler(sock) { sock.on('error', function(err) { assert.strictEqual(err.code, 'ECONNRESET'); }); - timer = setTimeout(function () { + timer = setTimeout(function() { sock.end('hello\n'); }, 100); } @@ -26,7 +27,7 @@ var net = require('net'), assert = require('assert'), PORT = common.PORT; -console.log('We should do '+ todo +' requests'); +console.log('We should do ' + todo + ' requests'); var server = net.createServer(serverHandler); server.listen(PORT, getall); @@ -35,7 +36,7 @@ function getall() { if (count >= todo) return; - (function(){ + (function() { var req = net.connect(PORT, '127.0.0.1'); req.resume(); req.setTimeout(10, function() { @@ -55,7 +56,7 @@ function getall() { for (var i = 0; i < 10; i++) getall(); -function afterGC(){ +function afterGC() { countGC ++; } diff --git a/test/internet/test-dgram-broadcast-multi-process.js b/test/internet/test-dgram-broadcast-multi-process.js index d60fb0bd3442c2..4cf5d7226f2c50 100644 --- a/test/internet/test-dgram-broadcast-multi-process.js +++ b/test/internet/test-dgram-broadcast-multi-process.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), dgram = require('dgram'), @@ -144,7 +145,7 @@ if (process.argv[2] !== 'child') { // bind the address explicitly for sending // INADDR_BROADCAST to only one interface sendSocket.bind(common.PORT, bindAddress); - sendSocket.on('listening', function () { + sendSocket.on('listening', function() { sendSocket.setBroadcast(true); }); @@ -162,9 +163,7 @@ if (process.argv[2] !== 'child') { sendSocket.send(buf, 0, buf.length, common.PORT, LOCAL_BROADCAST_HOST, function(err) { - if (err) throw err; - console.error('[PARENT] sent %s to %s:%s', util.inspect(buf.toString()), LOCAL_BROADCAST_HOST, common.PORT); diff --git a/test/internet/test-dgram-multicast-multi-process.js b/test/internet/test-dgram-multicast-multi-process.js index 66c92b285c2a4c..05acb844e54490 100644 --- a/test/internet/test-dgram-multicast-multi-process.js +++ b/test/internet/test-dgram-multicast-multi-process.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), dgram = require('dgram'), @@ -129,7 +130,7 @@ if (process.argv[2] !== 'child') { sendSocket.bind(); // The socket is actually created async now - sendSocket.on('listening', function () { + sendSocket.on('listening', function() { sendSocket.setTTL(1); sendSocket.setBroadcast(true); sendSocket.setMulticastTTL(1); @@ -206,7 +207,7 @@ if (process.argv[2] === 'child') { listenSocket.bind(common.PORT); - listenSocket.on('listening', function () { + listenSocket.on('listening', function() { listenSocket.addMembership(LOCAL_BROADCAST_HOST); }); } diff --git a/test/internet/test-dns-txt-sigsegv.js b/test/internet/test-dns-txt-sigsegv.js index 75d34c21c06dd8..eba5c66c464981 100644 --- a/test/internet/test-dns-txt-sigsegv.js +++ b/test/internet/test-dns-txt-sigsegv.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dns = require('dns'); diff --git a/test/internet/test-dns.js b/test/internet/test-dns.js index b980b822c112b4..eb7bab85475b2a 100644 --- a/test/internet/test-dns.js +++ b/test/internet/test-dns.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'), dns = require('dns'), @@ -500,7 +501,8 @@ TEST(function test_lookup_null_all(done) { TEST(function test_lookup_all_ipv4(done) { - var req = dns.lookup('www.google.com', {all: true, family: 4}, function(err, ips) { + var req = dns.lookup('www.google.com', {all: true, family: 4}, + function(err, ips) { if (err) throw err; assert.ok(Array.isArray(ips)); assert.ok(ips.length > 0); @@ -518,7 +520,8 @@ TEST(function test_lookup_all_ipv4(done) { TEST(function test_lookup_all_ipv6(done) { - var req = dns.lookup('www.google.com', {all: true, family: 6}, function(err, ips) { + var req = dns.lookup('www.google.com', {all: true, family: 6}, + function(err, ips) { if (err) throw err; assert.ok(Array.isArray(ips)); assert.ok(ips.length > 0); diff --git a/test/internet/test-http-dns-fail.js b/test/internet/test-http-dns-fail.js index 7d1cfbf630472d..151597de14cb0e 100644 --- a/test/internet/test-http-dns-fail.js +++ b/test/internet/test-http-dns-fail.js @@ -1,3 +1,4 @@ +'use strict'; /* * Repeated requests for a domain that fails to resolve * should trigger the error event after each attempt. diff --git a/test/internet/test-http-https-default-ports.js b/test/internet/test-http-https-default-ports.js index 26732ee086f1fa..1133221e6b7d44 100644 --- a/test/internet/test-http-https-default-ports.js +++ b/test/internet/test-http-https-default-ports.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/internet/test-net-connect-timeout.js b/test/internet/test-net-connect-timeout.js index a55cf5e4bbf260..d122229397fd75 100644 --- a/test/internet/test-net-connect-timeout.js +++ b/test/internet/test-net-connect-timeout.js @@ -1,3 +1,4 @@ +'use strict'; // This example attempts to time out before the connection is established // https://groups.google.com/forum/#!topic/nodejs/UE0ZbfLt6t8 // https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw diff --git a/test/internet/test-net-connect-unref.js b/test/internet/test-net-connect-unref.js index dc0462ffd0238b..a712490d31f566 100644 --- a/test/internet/test-net-connect-unref.js +++ b/test/internet/test-net-connect-unref.js @@ -1,9 +1,10 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); var client, killed = false, ended = false; -var TIMEOUT = 10 * 1000 +var TIMEOUT = 10 * 1000; client = net.createConnection(53, '8.8.8.8', function() { client.unref(); diff --git a/test/internet/test-tls-connnect-melissadata.js b/test/internet/test-tls-connnect-melissadata.js index 61239c89c80c3f..96ff41af30cbcc 100644 --- a/test/internet/test-tls-connnect-melissadata.js +++ b/test/internet/test-tls-connnect-melissadata.js @@ -1,3 +1,4 @@ +'use strict'; // Test for authorized access to the server which has a cross root // certification between Starfield Class 2 and ValiCert Class 2 var tls = require('tls'); diff --git a/test/internet/test-tls-reuse-host-from-socket.js b/test/internet/test-tls-reuse-host-from-socket.js index 2f6392ce83455a..f3864908155f0e 100644 --- a/test/internet/test-tls-reuse-host-from-socket.js +++ b/test/internet/test-tls-reuse-host-from-socket.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/2100bytes.js b/test/message/2100bytes.js index 59fe3c152325ad..b05f5e9e1d7168 100644 --- a/test/message/2100bytes.js +++ b/test/message/2100bytes.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); diff --git a/test/message/error_exit.js b/test/message/error_exit.js index 51c25697494878..7805fd21935377 100644 --- a/test/message/error_exit.js +++ b/test/message/error_exit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/eval_messages.js b/test/message/eval_messages.js index 157cf881f60e6f..603acafe0936c4 100644 --- a/test/message/eval_messages.js +++ b/test/message/eval_messages.js @@ -1,3 +1,4 @@ +'use strict'; // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); diff --git a/test/message/hello_world.js b/test/message/hello_world.js index 996e08d51a2e62..1e6b030393c6cf 100644 --- a/test/message/hello_world.js +++ b/test/message/hello_world.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/max_tick_depth.js b/test/message/max_tick_depth.js index 1e43cae1c1670d..cacd795810605a 100644 --- a/test/message/max_tick_depth.js +++ b/test/message/max_tick_depth.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); process.maxTickDepth = 10; diff --git a/test/message/nexttick_throw.js b/test/message/nexttick_throw.js index 21361edf333abb..3c0e2d8e379fd9 100644 --- a/test/message/nexttick_throw.js +++ b/test/message/nexttick_throw.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/nexttick_throw.out b/test/message/nexttick_throw.out index baced2ce879dea..1dd60694a892b8 100644 --- a/test/message/nexttick_throw.out +++ b/test/message/nexttick_throw.out @@ -4,6 +4,7 @@ ^ ReferenceError: undefined_reference_error_maker is not defined at *test*message*nexttick_throw.js:*:* + at doNTCallback0 (node.js:*:*) at process._tickCallback (node.js:*:*) at Function.Module.runMain (module.js:*:*) at startup (node.js:*:*) diff --git a/test/message/stack_overflow.js b/test/message/stack_overflow.js index f822afd22c5757..7d1033c3ab2b1a 100644 --- a/test/message/stack_overflow.js +++ b/test/message/stack_overflow.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/stdin_messages.js b/test/message/stdin_messages.js index 8c4e47d00095e6..eefa9e756dc312 100644 --- a/test/message/stdin_messages.js +++ b/test/message/stdin_messages.js @@ -1,3 +1,4 @@ +'use strict'; // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); diff --git a/test/message/stdin_messages.out b/test/message/stdin_messages.out index cbdc1fdb125626..92d09a0a144428 100644 --- a/test/message/stdin_messages.out +++ b/test/message/stdin_messages.out @@ -12,6 +12,7 @@ SyntaxError: Strict mode code may not include a with statement at emitNone (events.js:*:*) at Socket.emit (events.js:*:*) at endReadableNT (_stream_readable.js:*:*) + at doNTCallback2 (node.js:*:*) at process._tickCallback (node.js:*:*) 42 42 @@ -29,7 +30,7 @@ Error: hello at emitNone (events.js:*:*) at Socket.emit (events.js:*:*) at endReadableNT (_stream_readable.js:*:*) - at process._tickCallback (node.js:*:*) + at doNTCallback2 (node.js:*:*) [stdin]:1 throw new Error("hello") @@ -44,7 +45,7 @@ Error: hello at emitNone (events.js:*:*) at Socket.emit (events.js:*:*) at endReadableNT (_stream_readable.js:*:*) - at process._tickCallback (node.js:*:*) + at doNTCallback2 (node.js:*:*) 100 [stdin]:1 @@ -60,7 +61,7 @@ ReferenceError: y is not defined at emitNone (events.js:*:*) at Socket.emit (events.js:*:*) at endReadableNT (_stream_readable.js:*:*) - at process._tickCallback (node.js:*:*) + at doNTCallback2 (node.js:*:*) [stdin]:1 var ______________________________________________; throw 10 diff --git a/test/message/throw_custom_error.js b/test/message/throw_custom_error.js index 34a007920dafea..270b37d14ddead 100644 --- a/test/message/throw_custom_error.js +++ b/test/message/throw_custom_error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/throw_custom_error.out b/test/message/throw_custom_error.out index f003972940053c..bfb928d48dd08e 100644 --- a/test/message/throw_custom_error.out +++ b/test/message/throw_custom_error.out @@ -1,5 +1,5 @@ before -*test*message*throw_custom_error.js:7 +*test*message*throw_custom_error.js:8 throw ({ name: 'MyCustomError', message: 'This is a custom message' }); ^ MyCustomError: This is a custom message diff --git a/test/message/throw_in_line_with_tabs.js b/test/message/throw_in_line_with_tabs.js index dc035c42cade3d..50c69ca681019d 100644 --- a/test/message/throw_in_line_with_tabs.js +++ b/test/message/throw_in_line_with_tabs.js @@ -1,9 +1,11 @@ +/* eslint-disable indent */ +'use strict'; var common = require('../common'); var assert = require('assert'); console.error('before'); -(function () { +(function() { // these lines should contain tab! throw ({ foo: 'bar' }); })(); diff --git a/test/message/throw_in_line_with_tabs.out b/test/message/throw_in_line_with_tabs.out index 11eadab34bead1..e83b05768433b8 100644 --- a/test/message/throw_in_line_with_tabs.out +++ b/test/message/throw_in_line_with_tabs.out @@ -1,5 +1,5 @@ before -*test*message*throw_in_line_with_tabs.js:8 +*test*message*throw_in_line_with_tabs.js:10 throw ({ foo: 'bar' }); ^ [object Object] diff --git a/test/message/throw_non_error.js b/test/message/throw_non_error.js index 817b557906a512..33e0a051d65a1d 100644 --- a/test/message/throw_non_error.js +++ b/test/message/throw_non_error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/throw_non_error.out b/test/message/throw_non_error.out index 4b39de5acfa7e5..c859d5f16a511e 100644 --- a/test/message/throw_non_error.out +++ b/test/message/throw_non_error.out @@ -1,5 +1,5 @@ before -*test*message*throw_non_error.js:7 +*test*message*throw_non_error.js:8 throw ({ foo: 'bar' }); ^ [object Object] diff --git a/test/message/throw_null.js b/test/message/throw_null.js index 27e86a8ff0e1e7..ab8fb565a61e54 100644 --- a/test/message/throw_null.js +++ b/test/message/throw_null.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/throw_null.out b/test/message/throw_null.out index be5cb3f7b8729a..eb3eeb1294e727 100644 --- a/test/message/throw_null.out +++ b/test/message/throw_null.out @@ -1,5 +1,5 @@ -*test*message*throw_null.js:4 +*test*message*throw_null.js:5 throw null; -^ +^ null diff --git a/test/message/throw_undefined.js b/test/message/throw_undefined.js index dcc54d74d2d3cc..f855cdd2f7dabd 100644 --- a/test/message/throw_undefined.js +++ b/test/message/throw_undefined.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/throw_undefined.out b/test/message/throw_undefined.out index 1aa6e15b37f4f5..27aedd9ee46f15 100644 --- a/test/message/throw_undefined.out +++ b/test/message/throw_undefined.out @@ -1,5 +1,5 @@ -*test*message*throw_undefined.js:4 +*test*message*throw_undefined.js:5 throw undefined; ^ undefined diff --git a/test/message/timeout_throw.js b/test/message/timeout_throw.js index 4ccf0bdd27dfce..aaf3fbc8d2f48f 100644 --- a/test/message/timeout_throw.js +++ b/test/message/timeout_throw.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/undefined_reference_in_new_context.js b/test/message/undefined_reference_in_new_context.js index 01d9698f22b257..7256c0d8e36088 100644 --- a/test/message/undefined_reference_in_new_context.js +++ b/test/message/undefined_reference_in_new_context.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/message/vm_display_runtime_error.js b/test/message/vm_display_runtime_error.js index 22c10d6022bd92..d01ab0b540b3cb 100644 --- a/test/message/vm_display_runtime_error.js +++ b/test/message/vm_display_runtime_error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/message/vm_display_syntax_error.js b/test/message/vm_display_syntax_error.js index b0172264e71ffc..179263478b84b8 100644 --- a/test/message/vm_display_syntax_error.js +++ b/test/message/vm_display_syntax_error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/message/vm_dont_display_runtime_error.js b/test/message/vm_dont_display_runtime_error.js index 7aa81844b8f4ed..6b4c824cbe5eff 100644 --- a/test/message/vm_dont_display_runtime_error.js +++ b/test/message/vm_dont_display_runtime_error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); @@ -5,17 +6,17 @@ var vm = require('vm'); console.error('beginning'); try { - vm.runInThisContext('throw new Error("boo!")', { - filename: 'test.vm', - displayErrors: false - }); + vm.runInThisContext('throw new Error("boo!")', { + filename: 'test.vm', + displayErrors: false + }); } catch (e) {} console.error('middle'); vm.runInThisContext('throw new Error("boo!")', { - filename: 'test.vm', - displayErrors: false + filename: 'test.vm', + displayErrors: false }); console.error('end'); diff --git a/test/message/vm_dont_display_syntax_error.js b/test/message/vm_dont_display_syntax_error.js index 724bea22148fdd..42b1ab14cba76f 100644 --- a/test/message/vm_dont_display_syntax_error.js +++ b/test/message/vm_dont_display_syntax_error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); @@ -5,17 +6,17 @@ var vm = require('vm'); console.error('beginning'); try { - vm.runInThisContext('var 5;', { - filename: 'test.vm', - displayErrors: false - }); + vm.runInThisContext('var 5;', { + filename: 'test.vm', + displayErrors: false + }); } catch (e) {} console.error('middle'); vm.runInThisContext('var 5;', { - filename: 'test.vm', - displayErrors: false + filename: 'test.vm', + displayErrors: false }); console.error('end'); diff --git a/test/parallel/test-arm-math-exp-regress-1376.js b/test/parallel/test-arm-math-exp-regress-1376.js index fa3e3bfae15881..2b81f599a753b2 100644 --- a/test/parallel/test-arm-math-exp-regress-1376.js +++ b/test/parallel/test-arm-math-exp-regress-1376.js @@ -1,4 +1,9 @@ +<<<<<<< HEAD // See https://github.com/iojs/io.js/issues/1376 +======= +'use strict'; +// See https://github.com/nodejs/io.js/issues/1376 +>>>>>>> f29762f... test: enable linting for tests // and https://code.google.com/p/v8/issues/detail?id=4019 Math.abs(-0.5); diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 1e2e8e6d557807..ce84eabc34e1d4 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var a = require('assert'); @@ -144,10 +145,14 @@ if (typeof Symbol === 'symbol') { } // primitive wrappers and object -assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), ['a']), a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), {0: 'a'}), a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, new Number(1), {}), a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, new Boolean(true), {}), a.AssertionError); +assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), ['a']), + a.AssertionError); +assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), {0: 'a'}), + a.AssertionError); +assert.doesNotThrow(makeBlock(a.deepEqual, new Number(1), {}), + a.AssertionError); +assert.doesNotThrow(makeBlock(a.deepEqual, new Boolean(true), {}), + a.AssertionError); //deepStrictEqual assert.doesNotThrow(makeBlock(a.deepStrictEqual, new Date(2000, 3, 14), @@ -313,9 +318,9 @@ try { assert.equal(true, threw, 'a.doesNotThrow is not catching type matching errors'); -assert.throws(function() {assert.ifError(new Error('test error'))}); -assert.doesNotThrow(function() {assert.ifError(null)}); -assert.doesNotThrow(function() {assert.ifError()}); +assert.throws(function() {assert.ifError(new Error('test error'));}); +assert.doesNotThrow(function() {assert.ifError(null);}); +assert.doesNotThrow(function() {assert.ifError();}); // make sure that validating using constructor really works threw = false; @@ -373,7 +378,7 @@ function testAssertionMessage(actual, expected) { } catch (e) { assert.equal(e.toString(), ['AssertionError:', expected, '==', '\'\''].join(' ')); - assert.ok(e.generatedMessage, "Message not marked as generated"); + assert.ok(e.generatedMessage, 'Message not marked as generated'); } } @@ -393,7 +398,7 @@ testAssertionMessage([1, 2, 3], '[ 1, 2, 3 ]'); testAssertionMessage(/a/, '/a/'); testAssertionMessage(/abc/gim, '/abc/gim'); testAssertionMessage(function f() {}, '[Function: f]'); -testAssertionMessage(function () {}, '[Function]'); +testAssertionMessage(function() {}, '[Function]'); testAssertionMessage({}, '{}'); testAssertionMessage(circular, '{ y: 1, x: [Circular] }'); testAssertionMessage({a: undefined, b: null}, '{ a: undefined, b: null }'); @@ -402,7 +407,7 @@ testAssertionMessage({a: NaN, b: Infinity, c: -Infinity}, // #2893 try { - assert.throws(function () { + assert.throws(function() { assert.ifError(null); }); } catch (e) { @@ -415,14 +420,14 @@ assert.ok(threw); try { assert.equal(1, 2); } catch (e) { - assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2') + assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2'); assert.ok(e.generatedMessage, 'Message not marked as generated'); } try { assert.equal(1, 2, 'oh no'); } catch (e) { - assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no') + assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no'); assert.equal(e.generatedMessage, false, 'Message incorrectly marked as generated'); } diff --git a/test/parallel/test-bad-unicode.js b/test/parallel/test-bad-unicode.js index ba31ba3e234970..6dcabc8fd47b96 100644 --- a/test/parallel/test-bad-unicode.js +++ b/test/parallel/test-bad-unicode.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'), exception = null; diff --git a/test/parallel/test-beforeexit-event-exit.js b/test/parallel/test-beforeexit-event-exit.js index 8d0d43d45bb4d4..43d213a8f95055 100644 --- a/test/parallel/test-beforeexit-event-exit.js +++ b/test/parallel/test-beforeexit-event-exit.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); process.on('beforeExit', function() { diff --git a/test/parallel/test-beforeexit-event.js b/test/parallel/test-beforeexit-event.js index 8bfdbe108eccb1..f3bd127b408b08 100644 --- a/test/parallel/test-beforeexit-event.js +++ b/test/parallel/test-beforeexit-event.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var net = require('net'); var util = require('util'); @@ -19,7 +20,7 @@ function tryImmediate() { function tryTimer() { console.log('set a timeout'); - setTimeout(function () { + setTimeout(function() { console.log('timeout cb, do another once beforeExit'); revivals++; process.once('beforeExit', tryListen); diff --git a/test/parallel/test-buffer-ascii.js b/test/parallel/test-buffer-ascii.js index e7625f3a0c5458..efc3a72c662595 100644 --- a/test/parallel/test-buffer-ascii.js +++ b/test/parallel/test-buffer-ascii.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-buffer-concat.js b/test/parallel/test-buffer-concat.js index 54c4b13cb9dc90..b023dba4cdd3e3 100644 --- a/test/parallel/test-buffer-concat.js +++ b/test/parallel/test-buffer-concat.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -14,7 +15,7 @@ var flatLongLen = Buffer.concat(long, 40); assert(flatZero.length === 0); assert(flatOne.toString() === 'asdf'); assert(flatOne === one[0]); -assert(flatLong.toString() === (new Array(10+1).join('asdf'))); -assert(flatLongLen.toString() === (new Array(10+1).join('asdf'))); +assert(flatLong.toString() === (new Array(10 + 1).join('asdf'))); +assert(flatLongLen.toString() === (new Array(10 + 1).join('asdf'))); -console.log("ok"); +console.log('ok'); diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index 32748dcaaab727..7ffbae525f8984 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-buffer-inspect.js b/test/parallel/test-buffer-inspect.js index f663d23edce8dc..707f778255ad51 100644 --- a/test/parallel/test-buffer-inspect.js +++ b/test/parallel/test-buffer-inspect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-buffer-iterator.js b/test/parallel/test-buffer-iterator.js index ab02934bf9e794..05371d6d793fed 100644 --- a/test/parallel/test-buffer-iterator.js +++ b/test/parallel/test-buffer-iterator.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-buffer-slice.js b/test/parallel/test-buffer-slice.js index 3d8f9c62d2ce36..53434eab8e3f8f 100644 --- a/test/parallel/test-buffer-slice.js +++ b/test/parallel/test-buffer-slice.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -7,5 +8,5 @@ var buff = new Buffer(Buffer.poolSize + 1); var slicedBuffer = buff.slice(); assert.equal(slicedBuffer.parent, buff, - "slicedBufffer should have its parent set to the original " + - " buffer"); + 'slicedBufffer should have its parent set to the original ' + + ' buffer'); diff --git a/test/parallel/test-buffer.js b/test/parallel/test-buffer.js index 3cdd862880207a..428629139720dc 100644 --- a/test/parallel/test-buffer.js +++ b/test/parallel/test-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -127,8 +128,8 @@ assert.strictEqual(Math.floor(c.length / 2), copied); for (var i = 0; i < Math.floor(c.length / 2); i++) { assert.strictEqual(b[b.length - Math.floor(c.length / 2) + i], c[i]); } -for (var i = Math.floor(c.length /2) + 1; i < c.length; i++) { - assert.strictEqual(c[c.length-1], c[i]); +for (var i = Math.floor(c.length / 2) + 1; i < c.length; i++) { + assert.strictEqual(c[c.length - 1], c[i]); } // try to copy 513 bytes, and check we don't overrun c @@ -843,7 +844,7 @@ Buffer(Buffer(0), 0, 0); // GH-5110 -(function () { +(function() { var buffer = new Buffer('test'), string = JSON.stringify(buffer); @@ -1068,7 +1069,7 @@ assert.equal(buf.readInt8(0), -1); // see https://github.com/joyent/node/issues/5881 SlowBuffer(0).slice(0, 1); // make sure a zero length slice doesn't set the .parent attribute - assert.equal(Buffer(5).slice(0,0).parent, undefined); + assert.equal(Buffer(5).slice(0, 0).parent, undefined); // and make sure a proper slice does have a parent assert.ok(typeof Buffer(5).slice(0, 5).parent === 'object'); })(); @@ -1087,7 +1088,7 @@ assert.throws(function() { (function() { var a = [0]; for (var i = 0; i < 7; ++i) a = a.concat(a); - a = a.map(function(_, i) { return i }); + a = a.map(function(_, i) { return i; }); var b = Buffer(a); var c = Buffer(b); assert.equal(b.length, a.length); @@ -1100,11 +1101,11 @@ assert.throws(function() { })(); -assert.throws(function () { +assert.throws(function() { new Buffer(smalloc.kMaxLength + 1); }, RangeError); -assert.throws(function () { +assert.throws(function() { new SlowBuffer(smalloc.kMaxLength + 1); }, RangeError); diff --git a/test/parallel/test-c-ares.js b/test/parallel/test-c-ares.js index 2c74a470443b42..739c3256fb33ae 100644 --- a/test/parallel/test-c-ares.js +++ b/test/parallel/test-c-ares.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-buffering.js b/test/parallel/test-child-process-buffering.js index 997e64248ababb..a37e1dbbbd7574 100644 --- a/test/parallel/test-child-process-buffering.js +++ b/test/parallel/test-child-process-buffering.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -23,7 +24,7 @@ function pwd(callback) { childExited = true; }); - child.on('close', function () { + child.on('close', function() { callback(output); pwd_called = true; childClosed = true; diff --git a/test/parallel/test-child-process-cwd.js b/test/parallel/test-child-process-cwd.js index 2ff459e9a33982..5d3f0d9496a313 100644 --- a/test/parallel/test-child-process-cwd.js +++ b/test/parallel/test-child-process-cwd.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; @@ -26,7 +27,7 @@ function testCwd(options, forCode, forData) { assert.strictEqual(forCode, code); }); - child.on('close', function () { + child.on('close', function() { forData && assert.strictEqual(forData, data.replace(/[\s\r\n]+$/, '')); returns--; }); diff --git a/test/parallel/test-child-process-default-options.js b/test/parallel/test-child-process-default-options.js index ee0cb59842b9be..93165ded6d165d 100644 --- a/test/parallel/test-child-process-default-options.js +++ b/test/parallel/test-child-process-default-options.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-detached.js b/test/parallel/test-child-process-detached.js index 1cc2a5022ed49a..25b811a8caa991 100644 --- a/test/parallel/test-child-process-detached.js +++ b/test/parallel/test-child-process-detached.js @@ -1,23 +1,25 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); var spawn = require('child_process').spawn; -var childPath = path.join(__dirname, '..', 'fixtures', 'parent-process-nonpersistent.js'); +var childPath = path.join(__dirname, '..', 'fixtures', + 'parent-process-nonpersistent.js'); var persistentPid = -1; var child = spawn(process.execPath, [ childPath ]); -child.stdout.on('data', function (data) { +child.stdout.on('data', function(data) { persistentPid = parseInt(data, 10); }); -process.on('exit', function () { +process.on('exit', function() { assert(persistentPid !== -1); - assert.throws(function () { + assert.throws(function() { process.kill(child.pid); }); - assert.doesNotThrow(function () { + assert.doesNotThrow(function() { process.kill(persistentPid); }); }); diff --git a/test/parallel/test-child-process-disconnect.js b/test/parallel/test-child-process-disconnect.js index 95b26a7c4ad125..fd5153f3965b21 100644 --- a/test/parallel/test-child-process-disconnect.js +++ b/test/parallel/test-child-process-disconnect.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; diff --git a/test/parallel/test-child-process-double-pipe.js b/test/parallel/test-child-process-double-pipe.js index cf40dedd8a6eb1..17b05791315994 100644 --- a/test/parallel/test-child-process-double-pipe.js +++ b/test/parallel/test-child-process-double-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var is_windows = process.platform === 'win32'; var common = require('../common'); @@ -95,5 +96,5 @@ sed.stdout.on('data', function(data) { }); sed.stdout.on('end', function(code) { - assert.equal(result, 'hellO' + os.EOL + 'nOde' + os.EOL +'wOrld' + os.EOL); + assert.equal(result, 'hellO' + os.EOL + 'nOde' + os.EOL + 'wOrld' + os.EOL); }); diff --git a/test/parallel/test-child-process-env.js b/test/parallel/test-child-process-env.js index a6a164a66c4c72..6f2051f1282b84 100644 --- a/test/parallel/test-child-process-env.js +++ b/test/parallel/test-child-process-env.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-exec-buffer.js b/test/parallel/test-child-process-exec-buffer.js index b680e3b3c1ee5a..0ab05080a2cb87 100644 --- a/test/parallel/test-child-process-exec-buffer.js +++ b/test/parallel/test-child-process-exec-buffer.js @@ -1,3 +1,4 @@ +'use strict'; require('../common'); var assert = require('assert'); var exec = require('child_process').exec; @@ -8,7 +9,7 @@ var success_count = 0; var str = 'hello'; // default encoding -var child = exec("echo " + str, function(err, stdout, stderr) { +var child = exec('echo ' + str, function(err, stdout, stderr) { assert.ok('string', typeof(stdout), 'Expected stdout to be a string'); assert.ok('string', typeof(stderr), 'Expected stderr to be a string'); assert.equal(str + os.EOL, stdout); @@ -17,7 +18,7 @@ var child = exec("echo " + str, function(err, stdout, stderr) { }); // no encoding (Buffers expected) -var child = exec("echo " + str, { +var child = exec('echo ' + str, { encoding: null }, function(err, stdout, stderr) { assert.ok(stdout instanceof Buffer, 'Expected stdout to be a Buffer'); diff --git a/test/parallel/test-child-process-exec-cwd.js b/test/parallel/test-child-process-exec-cwd.js index c91a35de0b8c4b..9e7039990e9dfc 100644 --- a/test/parallel/test-child-process-exec-cwd.js +++ b/test/parallel/test-child-process-exec-cwd.js @@ -1,3 +1,4 @@ +'use strict'; require('../common'); var assert = require('assert'); var exec = require('child_process').exec; diff --git a/test/parallel/test-child-process-exec-env.js b/test/parallel/test-child-process-exec-env.js index 6c8410b9a61793..eb554b459cabd8 100644 --- a/test/parallel/test-child-process-exec-env.js +++ b/test/parallel/test-child-process-exec-env.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; diff --git a/test/parallel/test-child-process-exec-error.js b/test/parallel/test-child-process-exec-error.js index 7605af98549911..b141fc3f2c09cc 100644 --- a/test/parallel/test-child-process-exec-error.js +++ b/test/parallel/test-child-process-exec-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var child_process = require('child_process'); diff --git a/test/parallel/test-child-process-exit-code.js b/test/parallel/test-child-process-exit-code.js index 61f298633f8116..feb2fe217566be 100644 --- a/test/parallel/test-child-process-exit-code.js +++ b/test/parallel/test-child-process-exit-code.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-child-process-fork-and-spawn.js b/test/parallel/test-child-process-fork-and-spawn.js index 68e8af0fc3e19f..d5255bf83ca8e0 100644 --- a/test/parallel/test-child-process-fork-and-spawn.js +++ b/test/parallel/test-child-process-fork-and-spawn.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-child-process-fork-close.js b/test/parallel/test-child-process-fork-close.js index eddfec5d521436..12b64cc4ff82ac 100644 --- a/test/parallel/test-child-process-fork-close.js +++ b/test/parallel/test-child-process-fork-close.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'), common = require('../common'), fork = require('child_process').fork, diff --git a/test/parallel/test-child-process-fork-dgram.js b/test/parallel/test-child-process-fork-dgram.js index bd21f3f748155b..8858966fde4975 100644 --- a/test/parallel/test-child-process-fork-dgram.js +++ b/test/parallel/test-child-process-fork-dgram.js @@ -1,3 +1,4 @@ +'use strict'; /* * The purpose of this test is to make sure that when forking a process, * sending a fd representing a UDP socket to the child and sending messages @@ -30,7 +31,7 @@ if (process.argv[2] === 'child') { if (msg === 'server') { server = clusterServer; - server.on('message', function () { + server.on('message', function() { process.send('gotMessage'); }); @@ -50,14 +51,14 @@ if (process.argv[2] === 'child') { var childGotMessage = false; var parentGotMessage = false; - server.on('message', function (msg, rinfo) { + server.on('message', function(msg, rinfo) { parentGotMessage = true; }); - server.on('listening', function () { + server.on('listening', function() { child.send('server', server); - child.once('message', function (msg) { + child.once('message', function(msg) { if (msg === 'gotMessage') { childGotMessage = true; } @@ -66,8 +67,8 @@ if (process.argv[2] === 'child') { sendMessages(); }); - var sendMessages = function () { - var timer = setInterval(function () { + var sendMessages = function() { + var timer = setInterval(function() { client.send(msg, 0, msg.length, common.PORT, '127.0.0.1', function(err) { if (err) throw err; } @@ -85,7 +86,7 @@ if (process.argv[2] === 'child') { }, 1); }; - var shutdown = function () { + var shutdown = function() { child.send('stop'); server.close(); @@ -94,7 +95,7 @@ if (process.argv[2] === 'child') { server.bind(common.PORT, '127.0.0.1'); - process.once('exit', function () { + process.once('exit', function() { assert(parentGotMessage); assert(childGotMessage); }); diff --git a/test/parallel/test-child-process-fork-exec-argv.js b/test/parallel/test-child-process-fork-exec-argv.js index 34292c551112c1..94703a736a110e 100644 --- a/test/parallel/test-child-process-fork-exec-argv.js +++ b/test/parallel/test-child-process-fork-exec-argv.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var child_process = require('child_process'); var spawn = child_process.spawn; @@ -16,11 +17,11 @@ if (process.argv[2] === 'fork') { var child = spawn(process.execPath, execArgv.concat(args)); var out = ''; - child.stdout.on('data', function (chunk) { + child.stdout.on('data', function(chunk) { out += chunk; }); - child.on('exit', function () { + child.on('exit', function() { assert.deepEqual(JSON.parse(out), execArgv); }); } diff --git a/test/parallel/test-child-process-fork-exec-path.js b/test/parallel/test-child-process-fork-exec-path.js index 72bb69316814de..cffb5ca05a6a78 100644 --- a/test/parallel/test-child-process-fork-exec-path.js +++ b/test/parallel/test-child-process-fork-exec-path.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var cp = require('child_process'); var fs = require('fs'); diff --git a/test/parallel/test-child-process-fork-net.js b/test/parallel/test-child-process-fork-net.js index a16fb85041b95f..09ec8e24b9b46c 100644 --- a/test/parallel/test-child-process-fork-net.js +++ b/test/parallel/test-child-process-fork-net.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; diff --git a/test/parallel/test-child-process-fork-net2.js b/test/parallel/test-child-process-fork-net2.js index 150e9cfc4544e9..95ec26a88d0de2 100644 --- a/test/parallel/test-child-process-fork-net2.js +++ b/test/parallel/test-child-process-fork-net2.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; diff --git a/test/parallel/test-child-process-fork-ref.js b/test/parallel/test-child-process-fork-ref.js index aa38ad7a21c5ad..b4066641bae970 100644 --- a/test/parallel/test-child-process-fork-ref.js +++ b/test/parallel/test-child-process-fork-ref.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; @@ -10,7 +11,7 @@ if (process.argv[2] === 'child') { process.send('2'); }, 200); - process.on('disconnect', function () { + process.on('disconnect', function() { process.stdout.write('3'); }); @@ -19,17 +20,17 @@ if (process.argv[2] === 'child') { var ipc = [], stdout = ''; - child.on('message', function (msg) { + child.on('message', function(msg) { ipc.push(msg); if (msg === '2') child.disconnect(); }); - child.stdout.on('data', function (chunk) { + child.stdout.on('data', function(chunk) { stdout += chunk; }); - child.once('exit', function () { + child.once('exit', function() { assert.deepEqual(ipc, ['1', '2']); assert.equal(stdout, '3'); }); diff --git a/test/parallel/test-child-process-fork-ref2.js b/test/parallel/test-child-process-fork-ref2.js index 3ccdfc18871055..8bc7e4c35541b2 100644 --- a/test/parallel/test-child-process-fork-ref2.js +++ b/test/parallel/test-child-process-fork-ref2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; @@ -8,17 +9,17 @@ if (process.argv[2] === 'child') { setTimeout(function() { console.log('child -> will this keep it alive?'); - process.on('message', function () { }); + process.on('message', function() { }); }, 400); } else { var child = fork(__filename, ['child']); - child.on('disconnect', function () { + child.on('disconnect', function() { console.log('parent -> disconnect'); }); - child.once('exit', function () { + child.once('exit', function() { console.log('parent -> exit'); }); } diff --git a/test/parallel/test-child-process-fork.js b/test/parallel/test-child-process-fork.js index 2ec9f402dd5d39..c35510e60c76f4 100644 --- a/test/parallel/test-child-process-fork.js +++ b/test/parallel/test-child-process-fork.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; diff --git a/test/parallel/test-child-process-fork3.js b/test/parallel/test-child-process-fork3.js index 8527257bc53684..fe0e68b6a6436e 100644 --- a/test/parallel/test-child-process-fork3.js +++ b/test/parallel/test-child-process-fork3.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var child_process = require('child_process'); diff --git a/test/parallel/test-child-process-internal.js b/test/parallel/test-child-process-internal.js index a1bb52f4b71185..c39dc93293aa8b 100644 --- a/test/parallel/test-child-process-internal.js +++ b/test/parallel/test-child-process-internal.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-ipc.js b/test/parallel/test-child-process-ipc.js index 712b1ee0a5e54c..7d0447569ffe73 100644 --- a/test/parallel/test-child-process-ipc.js +++ b/test/parallel/test-child-process-ipc.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-kill.js b/test/parallel/test-child-process-kill.js index 7e46aada8bbfad..948348add4abb0 100644 --- a/test/parallel/test-child-process-kill.js +++ b/test/parallel/test-child-process-kill.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-recv-handle.js b/test/parallel/test-child-process-recv-handle.js index 7f2f04f831dbf1..b992445f186383 100644 --- a/test/parallel/test-child-process-recv-handle.js +++ b/test/parallel/test-child-process-recv-handle.js @@ -1,3 +1,4 @@ +'use strict'; // Test that a Linux specific quirk in the handle passing protocol is handled // correctly. See https://github.com/joyent/node/issues/5330 for details. diff --git a/test/parallel/test-child-process-send-utf8.js b/test/parallel/test-child-process-send-utf8.js index 825913dc2ae4c4..7ba76e9bd1ddc8 100644 --- a/test/parallel/test-child-process-send-utf8.js +++ b/test/parallel/test-child-process-send-utf8.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; diff --git a/test/parallel/test-child-process-set-blocking.js b/test/parallel/test-child-process-set-blocking.js index af831b720b2eb0..3f09388265b89a 100644 --- a/test/parallel/test-child-process-set-blocking.js +++ b/test/parallel/test-child-process-set-blocking.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var ch = require('child_process'); diff --git a/test/parallel/test-child-process-silent.js b/test/parallel/test-child-process-silent.js index e1e03d0973011e..3714d3758d0f22 100644 --- a/test/parallel/test-child-process-silent.js +++ b/test/parallel/test-child-process-silent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var childProcess = require('child_process'); diff --git a/test/parallel/test-child-process-spawn-error.js b/test/parallel/test-child-process-spawn-error.js index fe279dc6e586af..1398dac165319c 100644 --- a/test/parallel/test-child-process-spawn-error.js +++ b/test/parallel/test-child-process-spawn-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var fs = require('fs'); var spawn = require('child_process').spawn; @@ -10,7 +11,7 @@ var spawnargs = ['bar']; assert.equal(common.fileExists(enoentPath), false); var enoentChild = spawn(enoentPath, spawnargs); -enoentChild.on('error', function (err) { +enoentChild.on('error', function(err) { assert.equal(err.code, 'ENOENT'); assert.equal(err.errno, 'ENOENT'); assert.equal(err.syscall, 'spawn ' + enoentPath); diff --git a/test/parallel/test-child-process-spawn-typeerror.js b/test/parallel/test-child-process-spawn-typeerror.js index b95b208eb0c87e..35c190353bd1b8 100644 --- a/test/parallel/test-child-process-spawn-typeerror.js +++ b/test/parallel/test-child-process-spawn-typeerror.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var child_process = require('child_process'); var spawn = child_process.spawn; diff --git a/test/parallel/test-child-process-spawnsync-env.js b/test/parallel/test-child-process-spawnsync-env.js index 0ebc66a7459cfe..bc7c5aa3dd6c14 100644 --- a/test/parallel/test-child-process-spawnsync-env.js +++ b/test/parallel/test-child-process-spawnsync-env.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cp = require('child_process'); diff --git a/test/parallel/test-child-process-spawnsync-input.js b/test/parallel/test-child-process-spawnsync-input.js index e85e9da1fbade9..4118b74dc35f6c 100644 --- a/test/parallel/test-child-process-spawnsync-input.js +++ b/test/parallel/test-child-process-spawnsync-input.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var os = require('os'); diff --git a/test/parallel/test-child-process-spawnsync-timeout.js b/test/parallel/test-child-process-spawnsync-timeout.js index f5b5987e4d1eaf..34c69a1fc597d2 100644 --- a/test/parallel/test-child-process-spawnsync-timeout.js +++ b/test/parallel/test-child-process-spawnsync-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -15,7 +16,8 @@ switch (process.argv[2]) { break; default: var start = Date.now(); - var ret = spawnSync(process.execPath, [__filename, 'child'], {timeout: TIMER}); + var ret = spawnSync(process.execPath, [__filename, 'child'], + {timeout: TIMER}); assert.strictEqual(ret.error.errno, 'ETIMEDOUT'); console.log(ret); var end = Date.now() - start; diff --git a/test/parallel/test-child-process-spawnsync.js b/test/parallel/test-child-process-spawnsync.js index 67b07ed481889c..b6f4d31b5c158c 100644 --- a/test/parallel/test-child-process-spawnsync.js +++ b/test/parallel/test-child-process-spawnsync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -20,7 +21,8 @@ var ret = spawnSync('sleep', ['1']); var stop = process.hrtime(start); assert.strictEqual(ret.status, 0, 'exit status should be zero'); console.log('sleep exited', stop); -assert.strictEqual(stop[0], 1, 'sleep should not take longer or less than 1 second'); +assert.strictEqual(stop[0], 1, + 'sleep should not take longer or less than 1 second'); // Error test when command does not exist var ret_err = spawnSync('command_does_not_exist', ['bar']).error; diff --git a/test/parallel/test-child-process-stdin-ipc.js b/test/parallel/test-child-process-stdin-ipc.js index 2758087deac814..d2347849dd5b9b 100644 --- a/test/parallel/test-child-process-stdin-ipc.js +++ b/test/parallel/test-child-process-stdin-ipc.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-stdin.js b/test/parallel/test-child-process-stdin.js index f2a5e1836a6e1d..ba3ef0e0c1c689 100644 --- a/test/parallel/test-child-process-stdin.js +++ b/test/parallel/test-child-process-stdin.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -48,7 +49,7 @@ cat.on('exit', function(status) { exitStatus = status; }); -cat.on('close', function () { +cat.on('close', function() { closed = true; if (is_windows) { assert.equal('hello world\r\n', response); diff --git a/test/parallel/test-child-process-stdio-big-write-end.js b/test/parallel/test-child-process-stdio-big-write-end.js index 631cecc33d74b1..5ae85acc54d9dd 100644 --- a/test/parallel/test-child-process-stdio-big-write-end.js +++ b/test/parallel/test-child-process-stdio-big-write-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var BUFSIZE = 1024; diff --git a/test/parallel/test-child-process-stdio-inherit.js b/test/parallel/test-child-process-stdio-inherit.js index 15a504099263c8..8cf08a7bd5fa71 100644 --- a/test/parallel/test-child-process-stdio-inherit.js +++ b/test/parallel/test-child-process-stdio-inherit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-child-process-stdio.js b/test/parallel/test-child-process-stdio.js index 7292007f1a207e..1ff6e4d914f7ec 100644 --- a/test/parallel/test-child-process-stdio.js +++ b/test/parallel/test-child-process-stdio.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-child-process-stdout-flush-exit.js b/test/parallel/test-child-process-stdout-flush-exit.js index eba8927204f71c..0d4e3538ceb3f0 100644 --- a/test/parallel/test-child-process-stdout-flush-exit.js +++ b/test/parallel/test-child-process-stdout-flush-exit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -21,14 +22,14 @@ if (process.argv[2] === 'child') { var gotBye = false; child.stderr.setEncoding('utf8'); - child.stderr.on('data', function (data) { + child.stderr.on('data', function(data) { console.log('parent stderr: ' + data); assert.ok(false); }); // check if we receive both 'hello' at start and 'goodbye' at end child.stdout.setEncoding('utf8'); - child.stdout.on('data', function (data) { + child.stdout.on('data', function(data) { if (data.slice(0, 6) == 'hello\n') { gotHello = true; } else if (data.slice(data.length - 8) == 'goodbye\n') { @@ -38,7 +39,7 @@ if (process.argv[2] === 'child') { } }); - child.on('close', function (data) { + child.on('close', function(data) { assert(gotHello); assert(gotBye); }); diff --git a/test/parallel/test-child-process-stdout-flush.js b/test/parallel/test-child-process-stdout-flush.js index 58d6a8f46a4b9d..8300f4bbc7cbf3 100644 --- a/test/parallel/test-child-process-stdout-flush.js +++ b/test/parallel/test-child-process-stdout-flush.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index fd9cd410d5ea93..10a77c4a67b8a4 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -1,3 +1,4 @@ +'use strict'; if (module.parent) { // signal we've been loaded as a module console.log('Loaded as a module, exiting with status code 42.'); diff --git a/test/parallel/test-cluster-basic.js b/test/parallel/test-cluster-basic.js index 75ed9d3a155349..60bd27b24eee89 100644 --- a/test/parallel/test-cluster-basic.js +++ b/test/parallel/test-cluster-basic.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-bind-privileged-port.js b/test/parallel/test-cluster-bind-privileged-port.js index 3a75250c53f811..b51367aa4229a3 100644 --- a/test/parallel/test-cluster-bind-privileged-port.js +++ b/test/parallel/test-cluster-bind-privileged-port.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-bind-twice.js b/test/parallel/test-cluster-bind-twice.js index db1ea8874f4d17..ec6faa83c1151b 100644 --- a/test/parallel/test-cluster-bind-twice.js +++ b/test/parallel/test-cluster-bind-twice.js @@ -1,3 +1,4 @@ +'use strict'; // This test starts two clustered HTTP servers on the same port. It expects the // first cluster to succeed and the second cluster to fail with EADDRINUSE. // diff --git a/test/parallel/test-cluster-dgram-1.js b/test/parallel/test-cluster-dgram-1.js index dada58017f5130..bccc39637bb79a 100644 --- a/test/parallel/test-cluster-dgram-1.js +++ b/test/parallel/test-cluster-dgram-1.js @@ -1,3 +1,4 @@ +'use strict'; var NUM_WORKERS = 4; var PACKETS_PER_WORKER = 10; @@ -8,7 +9,7 @@ var dgram = require('dgram'); if (process.platform === 'win32') { - console.warn("dgram clustering is currently not supported on windows."); + console.warn('dgram clustering is currently not supported on windows.'); process.exit(0); } diff --git a/test/parallel/test-cluster-dgram-2.js b/test/parallel/test-cluster-dgram-2.js index 68de38e7c33c61..db4f986f2db64f 100644 --- a/test/parallel/test-cluster-dgram-2.js +++ b/test/parallel/test-cluster-dgram-2.js @@ -1,3 +1,4 @@ +'use strict'; var NUM_WORKERS = 4; var PACKETS_PER_WORKER = 10; @@ -8,7 +9,7 @@ var dgram = require('dgram'); if (process.platform === 'win32') { - console.warn("dgram clustering is currently not supported on windows."); + console.warn('dgram clustering is currently not supported on windows.'); process.exit(0); } @@ -61,5 +62,6 @@ function worker() { for (var i = 0; i < PACKETS_PER_WORKER; i++) socket.send(buf, 0, buf.length, common.PORT, '127.0.0.1'); - console.log('worker %d sent %d packets', cluster.worker.id, PACKETS_PER_WORKER); + console.log('worker %d sent %d packets', cluster.worker.id, + PACKETS_PER_WORKER); } diff --git a/test/parallel/test-cluster-disconnect-before-exit.js b/test/parallel/test-cluster-disconnect-before-exit.js index d249296bab740a..8f63bcd1134310 100644 --- a/test/parallel/test-cluster-disconnect-before-exit.js +++ b/test/parallel/test-cluster-disconnect-before-exit.js @@ -1,3 +1,4 @@ +'use strict'; var cluster = require('cluster'); if (cluster.isMaster) { diff --git a/test/parallel/test-cluster-disconnect-idle-worker.js b/test/parallel/test-cluster-disconnect-idle-worker.js index 28cdd2de4eaf50..e18c05004467b7 100644 --- a/test/parallel/test-cluster-disconnect-idle-worker.js +++ b/test/parallel/test-cluster-disconnect-idle-worker.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-disconnect-unshared-tcp.js b/test/parallel/test-cluster-disconnect-unshared-tcp.js index 6fccc58c095930..a927b5da9fe1b4 100644 --- a/test/parallel/test-cluster-disconnect-unshared-tcp.js +++ b/test/parallel/test-cluster-disconnect-unshared-tcp.js @@ -1,3 +1,4 @@ +'use strict'; process.env.NODE_CLUSTER_SCHED_POLICY = 'none'; var cluster = require('cluster'); @@ -16,7 +17,7 @@ if (cluster.isMaster) { } } else { if (process.env.BOUND === 'y') { - var source = net.createServer() + var source = net.createServer(); source.listen(0); } diff --git a/test/parallel/test-cluster-disconnect-unshared-udp.js b/test/parallel/test-cluster-disconnect-unshared-udp.js index a40c386918b156..f90152cf68f1a7 100644 --- a/test/parallel/test-cluster-disconnect-unshared-udp.js +++ b/test/parallel/test-cluster-disconnect-unshared-udp.js @@ -1,3 +1,4 @@ +'use strict'; if (process.platform === 'win32') { console.log('skipping test on windows, where clustered dgram is ENOTSUP'); process.exit(0); diff --git a/test/parallel/test-cluster-disconnect-with-no-workers.js b/test/parallel/test-cluster-disconnect-with-no-workers.js index e07f5af99ddf9f..1c99461bfa4fc5 100644 --- a/test/parallel/test-cluster-disconnect-with-no-workers.js +++ b/test/parallel/test-cluster-disconnect-with-no-workers.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-disconnect.js b/test/parallel/test-cluster-disconnect.js index c557256dcb3bfe..0f19d534aafd89 100644 --- a/test/parallel/test-cluster-disconnect.js +++ b/test/parallel/test-cluster-disconnect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-eaccess.js b/test/parallel/test-cluster-eaccess.js index 1be28a38559b0b..ad4de97e389ec5 100644 --- a/test/parallel/test-cluster-eaccess.js +++ b/test/parallel/test-cluster-eaccess.js @@ -1,5 +1,7 @@ -// test that errors propagated from cluster children are properly received in their master -// creates an EADDRINUSE condition by also forking a child process to listen on a socket +'use strict'; +// test that errors propagated from cluster children are properly +// received in their master creates an EADDRINUSE condition by also +// forking a child process to listen on a socket var common = require('../common'); var assert = require('assert'); @@ -27,7 +29,8 @@ if (cluster.isMaster) { assert.equal(gotError, 1); }); } else { - var cp = fork(common.fixturesDir + '/listen-on-socket-and-exit.js', { stdio: 'inherit' }); + var cp = fork(common.fixturesDir + '/listen-on-socket-and-exit.js', + { stdio: 'inherit' }); // message from the child indicates it's ready and listening cp.on('message', function() { diff --git a/test/parallel/test-cluster-eaddrinuse.js b/test/parallel/test-cluster-eaddrinuse.js index c43259c5631bcf..509dbb664e1d5d 100644 --- a/test/parallel/test-cluster-eaddrinuse.js +++ b/test/parallel/test-cluster-eaddrinuse.js @@ -1,3 +1,4 @@ +'use strict'; // Check that having a worker bind to a port that's already taken doesn't // leave the master process in a confused state. Releasing the port and // trying again should Just Work[TM]. diff --git a/test/parallel/test-cluster-fork-env.js b/test/parallel/test-cluster-fork-env.js index ddcf7d236c9482..7749e42f608c60 100644 --- a/test/parallel/test-cluster-fork-env.js +++ b/test/parallel/test-cluster-fork-env.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-http-pipe.js b/test/parallel/test-cluster-http-pipe.js index b9706699615ac1..42ed3bee1eed3c 100644 --- a/test/parallel/test-cluster-http-pipe.js +++ b/test/parallel/test-cluster-http-pipe.js @@ -1,3 +1,4 @@ +'use strict'; // It is not possible to send pipe handles over the IPC pipe on Windows. if (process.platform === 'win32') { process.exit(0); diff --git a/test/parallel/test-cluster-master-error.js b/test/parallel/test-cluster-master-error.js index e0e92e7cf9e2a4..e729963d7df6a9 100644 --- a/test/parallel/test-cluster-master-error.js +++ b/test/parallel/test-cluster-master-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-master-kill.js b/test/parallel/test-cluster-master-kill.js index a5c22855607104..89694ffd115bb4 100644 --- a/test/parallel/test-cluster-master-kill.js +++ b/test/parallel/test-cluster-master-kill.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-message.js b/test/parallel/test-cluster-message.js index 29c9e31159e62a..a72d1f079efaaa 100644 --- a/test/parallel/test-cluster-message.js +++ b/test/parallel/test-cluster-message.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-net-listen.js b/test/parallel/test-cluster-net-listen.js index 1d8e08c877481e..741cacc75897e3 100644 --- a/test/parallel/test-cluster-net-listen.js +++ b/test/parallel/test-cluster-net-listen.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-net-send.js b/test/parallel/test-cluster-net-send.js index 17d77171c50534..6190fb517e4d1a 100644 --- a/test/parallel/test-cluster-net-send.js +++ b/test/parallel/test-cluster-net-send.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; diff --git a/test/parallel/test-cluster-rr-domain-listen.js b/test/parallel/test-cluster-rr-domain-listen.js index fc26c93685a045..1328483abb72df 100644 --- a/test/parallel/test-cluster-rr-domain-listen.js +++ b/test/parallel/test-cluster-rr-domain-listen.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var cluster = require('cluster'); var domain = require('domain'); @@ -7,7 +8,7 @@ var domain = require('domain'); if (cluster.isWorker) { var d = domain.create(); - d.run(function () { }); + d.run(function() { }); var http = require('http'); http.Server(function() { }).listen(common.PORT, '127.0.0.1'); diff --git a/test/parallel/test-cluster-send-deadlock.js b/test/parallel/test-cluster-send-deadlock.js index 7fd465db5feb13..90b8c91695359b 100644 --- a/test/parallel/test-cluster-send-deadlock.js +++ b/test/parallel/test-cluster-send-deadlock.js @@ -1,3 +1,4 @@ +'use strict'; // Testing mutual send of handles: from master to worker, and from worker to // master. diff --git a/test/parallel/test-cluster-send-handle-twice.js b/test/parallel/test-cluster-send-handle-twice.js index 2d2c2cc588eaf8..f1552d79265a0c 100644 --- a/test/parallel/test-cluster-send-handle-twice.js +++ b/test/parallel/test-cluster-send-handle-twice.js @@ -1,3 +1,4 @@ +'use strict'; // Testing to send an handle twice to the parent process. var common = require('../common'); diff --git a/test/parallel/test-cluster-setup-master-argv.js b/test/parallel/test-cluster-setup-master-argv.js index a8274be2e924cb..b406c76cbbfe0b 100644 --- a/test/parallel/test-cluster-setup-master-argv.js +++ b/test/parallel/test-cluster-setup-master-argv.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-setup-master-cumulative.js b/test/parallel/test-cluster-setup-master-cumulative.js index cf2d8e90daac36..0376546d286b51 100644 --- a/test/parallel/test-cluster-setup-master-cumulative.js +++ b/test/parallel/test-cluster-setup-master-cumulative.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-setup-master-emit.js b/test/parallel/test-cluster-setup-master-emit.js index bef10d8cb81ba3..8b463ec97bff45 100644 --- a/test/parallel/test-cluster-setup-master-emit.js +++ b/test/parallel/test-cluster-setup-master-emit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-setup-master-multiple.js b/test/parallel/test-cluster-setup-master-multiple.js index da0c03c7320bc9..8ee6d091cd524a 100644 --- a/test/parallel/test-cluster-setup-master-multiple.js +++ b/test/parallel/test-cluster-setup-master-multiple.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-setup-master.js b/test/parallel/test-cluster-setup-master.js index 7cf9631146682b..c32b3ea6d3b18b 100644 --- a/test/parallel/test-cluster-setup-master.js +++ b/test/parallel/test-cluster-setup-master.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-shared-handle-bind-error.js b/test/parallel/test-cluster-shared-handle-bind-error.js index f327de994a1fc6..a93b07ba30e27b 100644 --- a/test/parallel/test-cluster-shared-handle-bind-error.js +++ b/test/parallel/test-cluster-shared-handle-bind-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-shared-handle-bind-privileged-port.js b/test/parallel/test-cluster-shared-handle-bind-privileged-port.js index 3bbe9fbf2f9cda..4fc4b078ad6409 100644 --- a/test/parallel/test-cluster-shared-handle-bind-privileged-port.js +++ b/test/parallel/test-cluster-shared-handle-bind-privileged-port.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-uncaught-exception.js b/test/parallel/test-cluster-uncaught-exception.js index 9f98d626c8634e..ec42773ef55856 100644 --- a/test/parallel/test-cluster-uncaught-exception.js +++ b/test/parallel/test-cluster-uncaught-exception.js @@ -1,3 +1,4 @@ +'use strict'; // Installing a custom uncaughtException handler should override the default // one that the cluster module installs. // https://github.com/joyent/node/issues/2556 diff --git a/test/parallel/test-cluster-worker-constructor.js b/test/parallel/test-cluster-worker-constructor.js index 331ab777481e59..e29dc01561903d 100644 --- a/test/parallel/test-cluster-worker-constructor.js +++ b/test/parallel/test-cluster-worker-constructor.js @@ -1,3 +1,4 @@ +'use strict'; // test-cluster-worker-constructor.js // validates correct behavior of the cluster.Worker constructor diff --git a/test/parallel/test-cluster-worker-death.js b/test/parallel/test-cluster-worker-death.js index d19704c58b3868..88a0f887cc2cab 100644 --- a/test/parallel/test-cluster-worker-death.js +++ b/test/parallel/test-cluster-worker-death.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-worker-destroy.js b/test/parallel/test-cluster-worker-destroy.js index 55ae0fc8c0c172..8e5ca63e13c6be 100644 --- a/test/parallel/test-cluster-worker-destroy.js +++ b/test/parallel/test-cluster-worker-destroy.js @@ -1,3 +1,4 @@ +'use strict'; /* * The goal of this test is to cover the Workers' implementation of * Worker.prototype.destroy. Worker.prototype.destroy is called within diff --git a/test/parallel/test-cluster-worker-disconnect.js b/test/parallel/test-cluster-worker-disconnect.js index 4bb9b163b64982..7f4038149cd7d1 100644 --- a/test/parallel/test-cluster-worker-disconnect.js +++ b/test/parallel/test-cluster-worker-disconnect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); @@ -8,6 +9,10 @@ if (cluster.isWorker) { }).listen(common.PORT, '127.0.0.1'); + cluster.worker.on('disconnect', function() { + process.exit(42); + }); + } else if (cluster.isMaster) { var checks = { @@ -18,6 +23,7 @@ if (cluster.isWorker) { }, worker: { emitDisconnect: false, + emitDisconnectInsideWorker: false, emitExit: false, state: false, suicideMode: false, @@ -59,9 +65,11 @@ if (cluster.isWorker) { }); // Check that the worker died - worker.once('exit', function() { + worker.once('exit', function(code) { checks.worker.emitExit = true; checks.worker.died = !alive(worker.process.pid); + checks.worker.emitDisconnectInsideWorker = code === 42; + process.nextTick(function() { process.exit(0); }); @@ -74,6 +82,8 @@ if (cluster.isWorker) { // events assert.ok(w.emitDisconnect, 'Disconnect event did not emit'); + assert.ok(w.emitDisconnectInsideWorker, + 'Disconnect event did not emit inside worker'); assert.ok(c.emitDisconnect, 'Disconnect event did not emit'); assert.ok(w.emitExit, 'Exit event did not emit'); assert.ok(c.emitExit, 'Exit event did not emit'); diff --git a/test/parallel/test-cluster-worker-events.js b/test/parallel/test-cluster-worker-events.js index fb3b8797e0deac..eb986556b69183 100644 --- a/test/parallel/test-cluster-worker-events.js +++ b/test/parallel/test-cluster-worker-events.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-worker-exit.js b/test/parallel/test-cluster-worker-exit.js index 1342a70d6f0c35..982b099cd1cfe1 100644 --- a/test/parallel/test-cluster-worker-exit.js +++ b/test/parallel/test-cluster-worker-exit.js @@ -1,3 +1,4 @@ +'use strict'; // test-cluster-worker-exit.js // verifies that, when a child process exits (by calling `process.exit(code)`) // - the parent receives the proper events in the proper order, no duplicates @@ -100,31 +101,31 @@ if (cluster.isWorker) { // some helper functions ... - function checkResults(expected_results, results) { - for (var k in expected_results) { - var actual = results[k], - expected = expected_results[k]; +function checkResults(expected_results, results) { + for (var k in expected_results) { + var actual = results[k], + expected = expected_results[k]; - if (typeof expected === 'function') { - expected(r[k]); + if (typeof expected === 'function') { + expected(r[k]); + } else { + var msg = (expected[1] || '') + + (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); + + if (expected && expected.length) { + assert.equal(actual, expected[0], msg); } else { - var msg = (expected[1] || '') + - (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); - - if (expected && expected.length) { - assert.equal(actual, expected[0], msg); - } else { - assert.equal(actual, expected, msg); - } + assert.equal(actual, expected, msg); } } } +} - function alive(pid) { - try { - process.kill(pid, 'SIGCONT'); - return true; - } catch (e) { - return false; - } +function alive(pid) { + try { + process.kill(pid, 'SIGCONT'); + return true; + } catch (e) { + return false; } +} diff --git a/test/parallel/test-cluster-worker-forced-exit.js b/test/parallel/test-cluster-worker-forced-exit.js index 144eb0dd3a3be8..54d2ce8a478303 100644 --- a/test/parallel/test-cluster-worker-forced-exit.js +++ b/test/parallel/test-cluster-worker-forced-exit.js @@ -1,5 +1,6 @@ +'use strict'; var assert = require('assert'); -var cluster = require('cluster') +var cluster = require('cluster'); var net = require('net'); var SENTINEL = 42; diff --git a/test/parallel/test-cluster-worker-init.js b/test/parallel/test-cluster-worker-init.js index 87e0ce040af98f..38886af5279a6d 100644 --- a/test/parallel/test-cluster-worker-init.js +++ b/test/parallel/test-cluster-worker-init.js @@ -1,3 +1,4 @@ +'use strict'; // test-cluster-worker-init.js // verifies that, when a child process is forked, the cluster.worker // object can receive messages as expected diff --git a/test/parallel/test-cluster-worker-isconnected.js b/test/parallel/test-cluster-worker-isconnected.js index ed839d49630491..4477278e31330a 100644 --- a/test/parallel/test-cluster-worker-isconnected.js +++ b/test/parallel/test-cluster-worker-isconnected.js @@ -1,3 +1,4 @@ +'use strict'; var cluster = require('cluster'); var assert = require('assert'); var util = require('util'); @@ -6,32 +7,32 @@ if (cluster.isMaster) { var worker = cluster.fork(); assert.ok(worker.isConnected(), - "isConnected() should return true as soon as the worker has " + - "been created."); + 'isConnected() should return true as soon as the worker has ' + + 'been created.'); worker.on('disconnect', function() { assert.ok(!worker.isConnected(), - "After a disconnect event has been emitted, " + - "isConncted should return false"); + 'After a disconnect event has been emitted, ' + + 'isConncted should return false'); }); worker.on('message', function(msg) { if (msg === 'readyToDisconnect') { worker.disconnect(); } - }) + }); } else { assert.ok(cluster.worker.isConnected(), - "isConnected() should return true from within a worker at all " + - "times."); + 'isConnected() should return true from within a worker at all ' + + 'times.'); cluster.worker.process.on('disconnect', function() { assert.ok(!cluster.worker.isConnected(), - "isConnected() should return false from within a worker " + - "after its underlying process has been disconnected from " + - "the master"); - }) + 'isConnected() should return false from within a worker ' + + 'after its underlying process has been disconnected from ' + + 'the master'); + }); process.send('readyToDisconnect'); } diff --git a/test/parallel/test-cluster-worker-isdead.js b/test/parallel/test-cluster-worker-isdead.js index 11766c597f8297..045a620a9efab7 100644 --- a/test/parallel/test-cluster-worker-isdead.js +++ b/test/parallel/test-cluster-worker-isdead.js @@ -1,3 +1,4 @@ +'use strict'; var cluster = require('cluster'); var assert = require('assert'); var net = require('net'); @@ -5,23 +6,23 @@ var net = require('net'); if (cluster.isMaster) { var worker = cluster.fork(); assert.ok(!worker.isDead(), - "isDead() should return false right after the worker has been " + - "created."); + 'isDead() should return false right after the worker has been ' + + 'created.'); worker.on('exit', function() { - assert.ok(!worker.isConnected(), - "After an event has been emitted, " + - "isDead should return true"); - }) + assert.ok(!worker.isConnected(), + 'After an event has been emitted, ' + + 'isDead should return true'); + }); worker.on('message', function(msg) { - if (msg === 'readyToDie') { - worker.kill(); - } + if (msg === 'readyToDie') { + worker.kill(); + } }); } else if (cluster.isWorker) { assert.ok(!cluster.worker.isDead(), - "isDead() should return false when called from within a worker"); + 'isDead() should return false when called from within a worker'); process.send('readyToDie'); } diff --git a/test/parallel/test-cluster-worker-kill.js b/test/parallel/test-cluster-worker-kill.js index 01da15fdca6a18..c73cf2dbd5216e 100644 --- a/test/parallel/test-cluster-worker-kill.js +++ b/test/parallel/test-cluster-worker-kill.js @@ -1,3 +1,4 @@ +'use strict'; // test-cluster-worker-kill.js // verifies that, when a child process is killed (we use SIGKILL) // - the parent receives the proper events in the proper order, no duplicates @@ -23,14 +24,16 @@ if (cluster.isWorker) { cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"], cluster_emitExit: [1, "the cluster did not emit 'exit'"], cluster_exitCode: [null, 'the cluster exited w/ incorrect exitCode'], - cluster_signalCode: [KILL_SIGNAL, 'the cluster exited w/ incorrect signalCode'], + cluster_signalCode: [KILL_SIGNAL, + 'the cluster exited w/ incorrect signalCode'], worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], worker_emitExit: [1, "the worker did not emit 'exit'"], worker_state: ['disconnected', 'the worker state is incorrect'], worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], worker_died: [true, 'the worker is still running'], worker_exitCode: [null, 'the worker exited w/ incorrect exitCode'], - worker_signalCode: [KILL_SIGNAL, 'the worker exited w/ incorrect signalCode'] + worker_signalCode: [KILL_SIGNAL, + 'the worker exited w/ incorrect signalCode'] }, results = { cluster_emitDisconnect: 0, @@ -98,30 +101,30 @@ if (cluster.isWorker) { // some helper functions ... - function checkResults(expected_results, results) { - for (var k in expected_results) { - var actual = results[k], - expected = expected_results[k]; - - if (typeof expected === 'function') { - expected(r[k]); +function checkResults(expected_results, results) { + for (var k in expected_results) { + var actual = results[k], + expected = expected_results[k]; + + if (typeof expected === 'function') { + expected(r[k]); + } else { + var msg = (expected[1] || '') + + (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); + if (expected && expected.length) { + assert.equal(actual, expected[0], msg); } else { - var msg = (expected[1] || '') + - (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); - if (expected && expected.length) { - assert.equal(actual, expected[0], msg); - } else { - assert.equal(actual, expected, msg); - } + assert.equal(actual, expected, msg); } } } +} - function alive(pid) { - try { - process.kill(pid, 'SIGCONT'); - return true; - } catch (e) { - return false; - } +function alive(pid) { + try { + process.kill(pid, 'SIGCONT'); + return true; + } catch (e) { + return false; } +} diff --git a/test/parallel/test-cluster-worker-no-exit.js b/test/parallel/test-cluster-worker-no-exit.js index 034a4952e88c59..b44831694c6bfa 100644 --- a/test/parallel/test-cluster-worker-no-exit.js +++ b/test/parallel/test-cluster-worker-no-exit.js @@ -1,5 +1,6 @@ +'use strict'; var assert = require('assert'); -var cluster = require('cluster') +var cluster = require('cluster'); var net = require('net'); var common = require('../common'); @@ -21,7 +22,7 @@ var server; if (cluster.isMaster) { server = net.createServer(function(conn) { server.close(); - worker.disconnect() + worker.disconnect(); worker.once('disconnect', function() { setTimeout(function() { conn.destroy(); diff --git a/test/parallel/test-common.js b/test/parallel/test-common.js index d15448bd36afff..7cbaf305d6e4f3 100644 --- a/test/parallel/test-common.js +++ b/test/parallel/test-common.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-console-instance.js b/test/parallel/test-console-instance.js index a91410b4091d47..a80c6e57e4b151 100644 --- a/test/parallel/test-console-instance.js +++ b/test/parallel/test-console-instance.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Stream = require('stream'); @@ -15,7 +16,7 @@ assert.equal('function', typeof Console); // make sure that the Console constructor throws // when not given a writable stream instance -assert.throws(function () { +assert.throws(function() { new Console(); }, /Console expects a writable stream/); diff --git a/test/parallel/test-console-not-call-toString.js b/test/parallel/test-console-not-call-toString.js index 9612a0f6ec0ddc..7846dbf2778b9c 100644 --- a/test/parallel/test-console-not-call-toString.js +++ b/test/parallel/test-console-not-call-toString.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-console.js b/test/parallel/test-console.js index 2e5060f38319d5..982c83851f072a 100644 --- a/test/parallel/test-console.js +++ b/test/parallel/test-console.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -7,17 +8,17 @@ assert.ok(process.stderr.writable); assert.equal('number', typeof process.stdout.fd); assert.equal('number', typeof process.stderr.fd); -assert.throws(function () { +assert.throws(function() { console.timeEnd('no such label'); }); -assert.doesNotThrow(function () { +assert.doesNotThrow(function() { console.time('label'); console.timeEnd('label'); }); // an Object with a custom .inspect() function -var custom_inspect = { foo: 'bar', inspect: function () { return 'inspect'; } }; +var custom_inspect = { foo: 'bar', inspect: function() { return 'inspect'; } }; var stdout_write = global.process.stdout.write; var strings = []; diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js index 0336871a56fa20..75d733ff98b9b1 100644 --- a/test/parallel/test-crypto-authenticated.js +++ b/test/parallel/test-crypto-authenticated.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -16,27 +17,33 @@ crypto.DEFAULT_ENCODING = 'buffer'; // var TEST_CASES = [ - { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', + { algo: 'aes-128-gcm', + key: '6970787039613669314d623455536234', iv: '583673497131313748307652', plain: 'Hello World!', ct: '4BE13896F64DFA2C2D0F2C76', tag: '272B422F62EB545EAA15B5FF84092447', tampered: false }, - { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', + { algo: 'aes-128-gcm', + key: '6970787039613669314d623455536234', iv: '583673497131313748307652', plain: 'Hello World!', ct: '4BE13896F64DFA2C2D0F2C76', aad: '000000FF', tag: 'BA2479F66275665A88CB7B15F43EB005', tampered: false }, - { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', + { algo: 'aes-128-gcm', + key: '6970787039613669314d623455536234', iv: '583673497131313748307652', plain: 'Hello World!', ct: '4BE13596F64DFA2C2D0FAC76', tag: '272B422F62EB545EAA15B5FF84092447', tampered: true }, - { algo: 'aes-256-gcm', key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', + { algo: 'aes-256-gcm', + key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', iv: '36306950306836764a6f4561', plain: 'Hello node.js world!', ct: '58E62CFE7B1D274111A82267EBB93866E72B6C2A', tag: '9BB44F663BADABACAE9720881FB1EC7A', tampered: false }, - { algo: 'aes-256-gcm', key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', + { algo: 'aes-256-gcm', + key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', iv: '36306950306836764a6f4561', plain: 'Hello node.js world!', ct: '58E62CFF7B1D274011A82267EBB93866E72B6C2B', tag: '9BB44F663BADABACAE9720881FB1EC7A', tampered: true }, - { algo: 'aes-192-gcm', key: '1ed2233fa2223ef5d7df08546049406c7305220bca40d4c9', + { algo: 'aes-192-gcm', + key: '1ed2233fa2223ef5d7df08546049406c7305220bca40d4c9', iv: '0e1791e9db3bd21a9122c416', plain: 'Hello node.js world!', password: 'very bad password', aad: '63616c76696e', ct: 'DDA53A4059AA17B88756984995F7BBA3C636CC44', diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js index dced72309371ab..8623ff477429da 100644 --- a/test/parallel/test-crypto-binary-default.js +++ b/test/parallel/test-crypto-binary-default.js @@ -1,3 +1,4 @@ +'use strict'; // This is the same as test/simple/test-crypto, but from before the shift // to use buffers by default. diff --git a/test/parallel/test-crypto-certificate.js b/test/parallel/test-crypto-certificate.js index 9c98fda2bd5120..ab0d4ca9dff0b3 100644 --- a/test/parallel/test-crypto-certificate.js +++ b/test/parallel/test-crypto-certificate.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-crypto-cipher-decipher.js b/test/parallel/test-crypto-cipher-decipher.js index e82a08d7031d0c..931cf339bbb612 100644 --- a/test/parallel/test-crypto-cipher-decipher.js +++ b/test/parallel/test-crypto-cipher-decipher.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -137,13 +138,13 @@ testCipher4(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); // not assert. See #4886. (function() { var c = crypto.createCipher('aes-256-cbc', 'secret'); - try { c.final('xxx') } catch (e) { /* Ignore. */ } - try { c.final('xxx') } catch (e) { /* Ignore. */ } - try { c.final('xxx') } catch (e) { /* Ignore. */ } + try { c.final('xxx'); } catch (e) { /* Ignore. */ } + try { c.final('xxx'); } catch (e) { /* Ignore. */ } + try { c.final('xxx'); } catch (e) { /* Ignore. */ } var d = crypto.createDecipher('aes-256-cbc', 'secret'); - try { d.final('xxx') } catch (e) { /* Ignore. */ } - try { d.final('xxx') } catch (e) { /* Ignore. */ } - try { d.final('xxx') } catch (e) { /* Ignore. */ } + try { d.final('xxx'); } catch (e) { /* Ignore. */ } + try { d.final('xxx'); } catch (e) { /* Ignore. */ } + try { d.final('xxx'); } catch (e) { /* Ignore. */ } })(); // Regression test for #5482: string to Cipher#update() should not assert. diff --git a/test/parallel/test-crypto-dh-odd-key.js b/test/parallel/test-crypto-dh-odd-key.js index 46b3c3d8c65c23..1c7f4f69bb4b50 100644 --- a/test/parallel/test-crypto-dh-odd-key.js +++ b/test/parallel/test-crypto-dh-odd-key.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index 9eccc2f357215c..4978ab2ebbcb1f 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var constants = require('constants'); @@ -58,7 +59,7 @@ assert.equal(secret1, secret3); // Run this one twice to make sure that the dh3 clears its error properly (function() { var c = crypto.createDecipher('aes-128-ecb', ''); - assert.throws(function() { c.final('utf8') }, /wrong final block length/); + assert.throws(function() { c.final('utf8'); }, /wrong final block length/); })(); assert.throws(function() { @@ -67,7 +68,7 @@ assert.throws(function() { (function() { var c = crypto.createDecipher('aes-128-ecb', ''); - assert.throws(function() { c.final('utf8') }, /wrong final block length/); + assert.throws(function() { c.final('utf8'); }, /wrong final block length/); })(); // Create a shared using a DH group. diff --git a/test/parallel/test-crypto-domain.js b/test/parallel/test-crypto-domain.js index 910e026d20c0ef..fe5e72982d53af 100644 --- a/test/parallel/test-crypto-domain.js +++ b/test/parallel/test-crypto-domain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); diff --git a/test/parallel/test-crypto-domains.js b/test/parallel/test-crypto-domains.js index eb5c77e12ca1eb..55c67b490dbae0 100644 --- a/test/parallel/test-crypto-domains.js +++ b/test/parallel/test-crypto-domains.js @@ -1,8 +1,9 @@ +'use strict'; var common = require('../common'); var domain = require('domain'); var assert = require('assert'); var d = domain.create(); -var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes'] +var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']; var errors = 0; if (!common.hasCrypto) { @@ -15,30 +16,30 @@ process.on('exit', function() { assert.equal(errors, 3); }); -d.on('error', function (e) { +d.on('error', function(e) { assert.equal(e.message, expect.shift()); errors += 1; }); -d.run(function () { +d.run(function() { one(); function one() { - crypto.pbkdf2('a', 'b', 1, 8, function () { + crypto.pbkdf2('a', 'b', 1, 8, function() { two(); throw new Error('pbkdf2'); }); } function two() { - crypto.randomBytes(4, function () { + crypto.randomBytes(4, function() { three(); throw new Error('randomBytes'); }); } function three() { - crypto.pseudoRandomBytes(4, function () { + crypto.pseudoRandomBytes(4, function() { throw new Error('pseudoRandomBytes'); }); } diff --git a/test/parallel/test-crypto-ecb.js b/test/parallel/test-crypto-ecb.js index f924dfd29b9bc3..f1541ddeb403dc 100644 --- a/test/parallel/test-crypto-ecb.js +++ b/test/parallel/test-crypto-ecb.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-crypto-from-binary.js b/test/parallel/test-crypto-from-binary.js index ae450645dda610..4c8d7338dd9770 100644 --- a/test/parallel/test-crypto-from-binary.js +++ b/test/parallel/test-crypto-from-binary.js @@ -1,3 +1,4 @@ +'use strict'; // This is the same as test/simple/test-crypto, but from before the shift // to use buffers by default. diff --git a/test/parallel/test-crypto-hash-stream-pipe.js b/test/parallel/test-crypto-hash-stream-pipe.js index 795abd49a0f597..23feccea3843ae 100644 --- a/test/parallel/test-crypto-hash-stream-pipe.js +++ b/test/parallel/test-crypto-hash-stream-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -7,7 +8,7 @@ if (!common.hasCrypto) { } var crypto = require('crypto'); -var stream = require('stream') +var stream = require('stream'); var s = new stream.PassThrough(); var h = crypto.createHash('sha1'); var expect = '15987e60950cf22655b9323bc1e281f9c4aff47e'; diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js index af323ac4f6496e..5c542406cb7112 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-crypto-hmac.js b/test/parallel/test-crypto-hmac.js index 1a90811fe87c9e..e234bd91606906 100644 --- a/test/parallel/test-crypto-hmac.js +++ b/test/parallel/test-crypto-hmac.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -56,7 +57,7 @@ var wikipedia = [ '4292c5ad' } }, -] +]; for (var i = 0, l = wikipedia.length; i < l; i++) { for (var hash in wikipedia[i]['hmac']) { diff --git a/test/parallel/test-crypto-padding-aes256.js b/test/parallel/test-crypto-padding-aes256.js index de5fb7ca8732c1..db75a07c9e1617 100644 --- a/test/parallel/test-crypto-padding-aes256.js +++ b/test/parallel/test-crypto-padding-aes256.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -15,15 +16,15 @@ function aes256(decipherFinal) { '0123456789abcdef0123456789abcdef', 'hex'); function encrypt(val, pad) { - var c = crypto.createCipheriv('aes256', key, iv); - c.setAutoPadding(pad); - return c.update(val, 'utf8', 'binary') + c.final('binary'); + var c = crypto.createCipheriv('aes256', key, iv); + c.setAutoPadding(pad); + return c.update(val, 'utf8', 'binary') + c.final('binary'); } function decrypt(val, pad) { - var c = crypto.createDecipheriv('aes256', key, iv); - c.setAutoPadding(pad); - return c.update(val, 'binary', 'utf8') + c[decipherFinal]('utf8'); + var c = crypto.createDecipheriv('aes256', key, iv); + c.setAutoPadding(pad); + return c.update(val, 'binary', 'utf8') + c[decipherFinal]('utf8'); } // echo 0123456789abcdef0123456789abcdef \ diff --git a/test/parallel/test-crypto-padding.js b/test/parallel/test-crypto-padding.js index 2cf78588f9da62..11b1729fde88cb 100644 --- a/test/parallel/test-crypto-padding.js +++ b/test/parallel/test-crypto-padding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-crypto-pbkdf2.js b/test/parallel/test-crypto-pbkdf2.js index 440c6162e3b26a..88be15b68cb348 100644 --- a/test/parallel/test-crypto-pbkdf2.js +++ b/test/parallel/test-crypto-pbkdf2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-crypto-random.js b/test/parallel/test-crypto-random.js index de1bfccf90d2fb..cac0c9b86cf2c1 100644 --- a/test/parallel/test-crypto-random.js +++ b/test/parallel/test-crypto-random.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index 65986b49c94789..127bbfb26df5dd 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js index 5cac8948dbd02f..fb811e7f12d0fc 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-crypto-stream.js b/test/parallel/test-crypto-stream.js index 75ea5b13a4c5df..fd970e061b00e1 100644 --- a/test/parallel/test-crypto-stream.js +++ b/test/parallel/test-crypto-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var stream = require('stream'); @@ -14,24 +15,24 @@ function Stream2buffer(callback) { stream.Writable.call(this); this._buffers = []; - this.once('finish', function () { + this.once('finish', function() { callback(null, Buffer.concat(this._buffers)); }); } util.inherits(Stream2buffer, stream.Writable); -Stream2buffer.prototype._write = function (data, encodeing, done) { +Stream2buffer.prototype._write = function(data, encodeing, done) { this._buffers.push(data); return done(null); }; // Create an md5 hash of "Hallo world" var hasher1 = crypto.createHash('md5'); - hasher1.pipe(new Stream2buffer(common.mustCall(function end(err, hash) { - assert.equal(err, null); - assert.equal(hash.toString('hex'), '06460dadb35d3d503047ce750ceb2d07'); - }))); - hasher1.end('Hallo world'); +hasher1.pipe(new Stream2buffer(common.mustCall(function end(err, hash) { + assert.equal(err, null); + assert.equal(hash.toString('hex'), '06460dadb35d3d503047ce750ceb2d07'); +}))); +hasher1.end('Hallo world'); // Simpler check for unpipe, setEncoding, pause and resume crypto.createHash('md5').unpipe({}); diff --git a/test/parallel/test-crypto-verify-failure.js b/test/parallel/test-crypto-verify-failure.js index 6190ae247dae2c..a4a9ec698197c0 100644 --- a/test/parallel/test-crypto-verify-failure.js +++ b/test/parallel/test-crypto-verify-failure.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -23,11 +24,11 @@ var canSend = true; var server = tls.Server(options, function(socket) { setImmediate(function() { - console.log('sending'); - verify(); - setImmediate(function() { - socket.destroy(); - }); + console.log('sending'); + verify(); + setImmediate(function() { + socket.destroy(); + }); }); }); diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index d8a5099bbd80ea..e3557943c63d82 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -118,7 +119,7 @@ assert.throws(function() { }, /Bad input string/); assert.throws(function() { - var private = [ + var priv = [ '-----BEGIN RSA PRIVATE KEY-----', 'MIGrAgEAAiEA+3z+1QNF2/unumadiwEr+C5vfhezsb3hp4jAnCNRpPcCAwEAAQIgQNriSQK4', 'EFwczDhMZp2dvbcz7OUUyt36z3S4usFPHSECEQD/41K7SujrstBfoCPzwC1xAhEA+5kt4BJy', @@ -127,7 +128,7 @@ assert.throws(function() { '-----END RSA PRIVATE KEY-----', '' ].join('\n'); - crypto.createSign('RSA-SHA256').update('test').sign(private); + crypto.createSign('RSA-SHA256').update('test').sign(priv); }, /RSA_sign:digest too big for rsa key/); // Make sure memory isn't released before being returned diff --git a/test/parallel/test-cwd-enoent-repl.js b/test/parallel/test-cwd-enoent-repl.js index 64538f80b963df..5f47b84be5b2f0 100644 --- a/test/parallel/test-cwd-enoent-repl.js +++ b/test/parallel/test-cwd-enoent-repl.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-cwd-enoent.js b/test/parallel/test-cwd-enoent.js index 6e7b02c85d8d12..0d0fde24814e83 100644 --- a/test/parallel/test-cwd-enoent.js +++ b/test/parallel/test-cwd-enoent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-debug-port-cluster.js b/test/parallel/test-debug-port-cluster.js index 96a6f6e7f405b7..5bec9dc720599e 100644 --- a/test/parallel/test-debug-port-cluster.js +++ b/test/parallel/test-debug-port-cluster.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; @@ -16,7 +17,7 @@ child.stderr.on('data', function(data) { var lines = data.toString().replace(/\r/g, '').trim().split('\n'); var line = lines[0]; - lines.forEach(function(ln) { console.log('> ' + ln) } ); + lines.forEach(function(ln) { console.log('> ' + ln); } ); if (line === 'all workers are running') { assertOutputLines(); @@ -33,8 +34,8 @@ process.on('exit', function onExit() { var assertOutputLines = common.mustCall(function() { var expectedLines = [ 'Debugger listening on port ' + port, - 'Debugger listening on port ' + (port+1), - 'Debugger listening on port ' + (port+2), + 'Debugger listening on port ' + (port + 1), + 'Debugger listening on port ' + (port + 2), ]; // Do not assume any particular order of output messages, @@ -42,7 +43,7 @@ var assertOutputLines = common.mustCall(function() { // start up outputLines.sort(); - assert.equal(outputLines.length, expectedLines.length) + assert.equal(outputLines.length, expectedLines.length); for (var i = 0; i < expectedLines.length; i++) assert.equal(outputLines[i], expectedLines[i]); }); diff --git a/test/parallel/test-debug-port-from-cmdline.js b/test/parallel/test-debug-port-from-cmdline.js index 4ed2e84918c8f0..deb7ae241a55fd 100644 --- a/test/parallel/test-debug-port-from-cmdline.js +++ b/test/parallel/test-debug-port-from-cmdline.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-debug-signal-cluster.js b/test/parallel/test-debug-signal-cluster.js index 772ee6f1e6f454..6572ef50afe845 100644 --- a/test/parallel/test-debug-signal-cluster.js +++ b/test/parallel/test-debug-signal-cluster.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-delayed-require.js b/test/parallel/test-delayed-require.js index 161f3d2ffa79ae..5fa82f236c1dd9 100644 --- a/test/parallel/test-delayed-require.js +++ b/test/parallel/test-delayed-require.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-dgram-address.js b/test/parallel/test-dgram-address.js index 6da1c6cda45c76..f128ce5110317b 100644 --- a/test/parallel/test-dgram-address.js +++ b/test/parallel/test-dgram-address.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-bind-default-address.js b/test/parallel/test-dgram-bind-default-address.js index 28db7d9fa61af1..03e8afb99132aa 100644 --- a/test/parallel/test-dgram-bind-default-address.js +++ b/test/parallel/test-dgram-bind-default-address.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-bind-shared-ports.js b/test/parallel/test-dgram-bind-shared-ports.js index 4cfe4b5f9af7f4..91a48a260fbd90 100644 --- a/test/parallel/test-dgram-bind-shared-ports.js +++ b/test/parallel/test-dgram-bind-shared-ports.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-dgram-bind.js b/test/parallel/test-dgram-bind.js index 72f2f2c2b052bb..6d35534cb5eb56 100644 --- a/test/parallel/test-dgram-bind.js +++ b/test/parallel/test-dgram-bind.js @@ -1,10 +1,11 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); var socket = dgram.createSocket('udp4'); -socket.on('listening', function () { +socket.on('listening', function() { socket.close(); }); diff --git a/test/parallel/test-dgram-bytes-length.js b/test/parallel/test-dgram-bytes-length.js index 9698a0b465e4b8..9f8c39eb04daaf 100644 --- a/test/parallel/test-dgram-bytes-length.js +++ b/test/parallel/test-dgram-bytes-length.js @@ -1,10 +1,12 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); var message = new Buffer('Some bytes'); var client = dgram.createSocket('udp4'); -client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) { +client.send(message, 0, message.length, 41234, 'localhost', + function(err, bytes) { assert.strictEqual(bytes, message.length); client.close(); }); diff --git a/test/parallel/test-dgram-close-is-not-callback.js b/test/parallel/test-dgram-close-is-not-callback.js index 94035af97027bb..6fc4901fa14404 100644 --- a/test/parallel/test-dgram-close-is-not-callback.js +++ b/test/parallel/test-dgram-close-is-not-callback.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-close.js b/test/parallel/test-dgram-close.js index bd4af66323c05b..7e9dd4ef52c402 100644 --- a/test/parallel/test-dgram-close.js +++ b/test/parallel/test-dgram-close.js @@ -1,3 +1,4 @@ +'use strict'; // Ensure that if a dgram socket is closed before the DNS lookup completes, it // won't crash. diff --git a/test/parallel/test-dgram-empty-packet.js b/test/parallel/test-dgram-empty-packet.js index a629df8e1bc564..797012b8839fb7 100644 --- a/test/parallel/test-dgram-empty-packet.js +++ b/test/parallel/test-dgram-empty-packet.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -22,15 +23,15 @@ function callback() { clearTimeout(timer); client.close(); } else if (callbacks > 2) { - throw new Error("the callbacks should be called only two times"); + throw new Error('the callbacks should be called only two times'); } } -client.on('message', function (buffer, bytes) { +client.on('message', function(buffer, bytes) { callback(); }); -client.send(new Buffer(1), 0, 0, common.PORT, "127.0.0.1", function (err, len) { +client.send(new Buffer(1), 0, 0, common.PORT, '127.0.0.1', function(err, len) { callback(); }); diff --git a/test/parallel/test-dgram-error-message-address.js b/test/parallel/test-dgram-error-message-address.js index 95b1e062e3f2a7..eca2ccce4f1b65 100644 --- a/test/parallel/test-dgram-error-message-address.js +++ b/test/parallel/test-dgram-error-message-address.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-exclusive-implicit-bind.js b/test/parallel/test-dgram-exclusive-implicit-bind.js index 057b891eb6d891..077e1812b99144 100644 --- a/test/parallel/test-dgram-exclusive-implicit-bind.js +++ b/test/parallel/test-dgram-exclusive-implicit-bind.js @@ -1,3 +1,4 @@ +'use strict'; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a diff --git a/test/parallel/test-dgram-implicit-bind.js b/test/parallel/test-dgram-implicit-bind.js index adf6f52b4974a0..8b78bd66c6f313 100644 --- a/test/parallel/test-dgram-implicit-bind.js +++ b/test/parallel/test-dgram-implicit-bind.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-listen-after-bind.js b/test/parallel/test-dgram-listen-after-bind.js index c5f09b84677872..2aac7ae9cf7588 100644 --- a/test/parallel/test-dgram-listen-after-bind.js +++ b/test/parallel/test-dgram-listen-after-bind.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); @@ -7,16 +8,16 @@ var socket = dgram.createSocket('udp4'); socket.bind(); var fired = false; -var timer = setTimeout(function () { +var timer = setTimeout(function() { socket.close(); }, 100); -socket.on('listening', function () { +socket.on('listening', function() { clearTimeout(timer); fired = true; socket.close(); }); -socket.on('close', function () { +socket.on('close', function() { assert(fired, 'listening should fire after bind'); }); diff --git a/test/parallel/test-dgram-msgsize.js b/test/parallel/test-dgram-msgsize.js index 474ab82f44a47f..6330e2a82bdcc5 100644 --- a/test/parallel/test-dgram-msgsize.js +++ b/test/parallel/test-dgram-msgsize.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-multicast-setTTL.js b/test/parallel/test-dgram-multicast-setTTL.js index d849945fab7837..f48fc7118ec3c1 100644 --- a/test/parallel/test-dgram-multicast-setTTL.js +++ b/test/parallel/test-dgram-multicast-setTTL.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), dgram = require('dgram'), @@ -5,7 +6,7 @@ var common = require('../common'), socket = dgram.createSocket('udp4'); socket.bind(common.PORT); -socket.on('listening', function () { +socket.on('listening', function() { socket.setMulticastTTL(16); //Try to set an invalid TTL (valid ttl is > 0 and < 256) diff --git a/test/parallel/test-dgram-oob-buffer.js b/test/parallel/test-dgram-oob-buffer.js index bbbdc4dafeee19..b64c7236afd4bc 100644 --- a/test/parallel/test-dgram-oob-buffer.js +++ b/test/parallel/test-dgram-oob-buffer.js @@ -1,3 +1,4 @@ +'use strict'; // Some operating systems report errors when an UDP message is sent to an // unreachable host. This error can be reported by sendto() and even by // recvfrom(). Node should not propagate this error to the user. diff --git a/test/parallel/test-dgram-pingpong.js b/test/parallel/test-dgram-pingpong.js index b7d7a0067e89e7..29ab92757bd817 100644 --- a/test/parallel/test-dgram-pingpong.js +++ b/test/parallel/test-dgram-pingpong.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Buffer = require('buffer').Buffer; diff --git a/test/parallel/test-dgram-ref.js b/test/parallel/test-dgram-ref.js index 8d100eb0783f55..d689a45e36dfa2 100644 --- a/test/parallel/test-dgram-ref.js +++ b/test/parallel/test-dgram-ref.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-regress-4496.js b/test/parallel/test-dgram-regress-4496.js index a200716c0fb8d8..fcb8d026bc547e 100644 --- a/test/parallel/test-dgram-regress-4496.js +++ b/test/parallel/test-dgram-regress-4496.js @@ -1,3 +1,4 @@ +'use strict'; // Remove this test once we support sending strings. var common = require('../common'); @@ -6,6 +7,6 @@ var dgram = require('dgram'); // Should throw but not crash. var socket = dgram.createSocket('udp4'); -assert.throws(function() { socket.send(true, 0, 1, 1, 'host') }, TypeError); -assert.throws(function() { socket.sendto(5, 0, 1, 1, 'host') }, TypeError); +assert.throws(function() { socket.send(true, 0, 1, 1, 'host'); }, TypeError); +assert.throws(function() { socket.sendto(5, 0, 1, 1, 'host'); }, TypeError); socket.close(); diff --git a/test/parallel/test-dgram-send-bad-arguments.js b/test/parallel/test-dgram-send-bad-arguments.js index ab18784ccc6905..ccd10e00555384 100644 --- a/test/parallel/test-dgram-send-bad-arguments.js +++ b/test/parallel/test-dgram-send-bad-arguments.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-send-callback-buffer-length.js b/test/parallel/test-dgram-send-callback-buffer-length.js index 5596a7242f3a6a..a34c5e2eb6b8db 100644 --- a/test/parallel/test-dgram-send-callback-buffer-length.js +++ b/test/parallel/test-dgram-send-callback-buffer-length.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -15,11 +16,11 @@ offset = 20; len = buf.length - offset; -client.send(buf, offset, len, common.PORT, "127.0.0.1", function (err, bytes) { - assert.notEqual(bytes, buf.length); - assert.equal(bytes, buf.length - offset); - clearTimeout(timer); - client.close(); +client.send(buf, offset, len, common.PORT, '127.0.0.1', function(err, bytes) { + assert.notEqual(bytes, buf.length); + assert.equal(bytes, buf.length - offset); + clearTimeout(timer); + client.close(); }); timer = setTimeout(function() { diff --git a/test/parallel/test-dgram-send-callback-recursive.js b/test/parallel/test-dgram-send-callback-recursive.js new file mode 100644 index 00000000000000..046545deff6da3 --- /dev/null +++ b/test/parallel/test-dgram-send-callback-recursive.js @@ -0,0 +1,39 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); + +const dgram = require('dgram'); +const client = dgram.createSocket('udp4'); +const chunk = 'abc'; +var recursiveCount = 0; +var received = 0; +const limit = 10; +const recursiveLimit = limit + 1; + +function onsend() { + if (recursiveCount > recursiveLimit) { + throw new Error('infinite loop detected'); + } + if (received < limit) { + client.send( + chunk, 0, chunk.length, common.PORT, common.localhostIPv4, onsend); + } + recursiveCount++; +} + +client.on('listening', function() { + onsend(); +}); + +client.on('message', function(buf, info) { + received++; + if (received === limit) { + client.close(); + } +}); + +client.on('close', common.mustCall(function() { + assert.equal(received, limit); +})); + +client.bind(common.PORT); diff --git a/test/parallel/test-dgram-send-empty-buffer.js b/test/parallel/test-dgram-send-empty-buffer.js index e2ca937d6afbb3..ab66e0545e611d 100644 --- a/test/parallel/test-dgram-send-empty-buffer.js +++ b/test/parallel/test-dgram-send-empty-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -16,13 +17,13 @@ client = dgram.createSocket('udp4'); client.bind(common.PORT); -client.on('message', function (buffer, bytes) { +client.on('message', function(buffer, bytes) { clearTimeout(timer); client.close(); }); buf = new Buffer(0); -client.send(buf, 0, 0, common.PORT, "127.0.0.1", function (err, len) { }); +client.send(buf, 0, 0, common.PORT, '127.0.0.1', function(err, len) { }); timer = setTimeout(function() { throw new Error('Timeout'); diff --git a/test/parallel/test-dgram-udp4.js b/test/parallel/test-dgram-udp4.js index cde49c1b1bc063..f81dec398f72d1 100644 --- a/test/parallel/test-dgram-udp4.js +++ b/test/parallel/test-dgram-udp4.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-dgram-unref.js b/test/parallel/test-dgram-unref.js index 94f7ba739c740c..2add3d28c49760 100644 --- a/test/parallel/test-dgram-unref.js +++ b/test/parallel/test-dgram-unref.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-dh-padding.js b/test/parallel/test-dh-padding.js index 3e30fd34e7713d..872653763239c4 100644 --- a/test/parallel/test-dh-padding.js +++ b/test/parallel/test-dh-padding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-dns-cares-domains.js b/test/parallel/test-dns-cares-domains.js index 5c6d07cfe5322a..cb651c5f5afb86 100644 --- a/test/parallel/test-dns-cares-domains.js +++ b/test/parallel/test-dns-cares-domains.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dns = require('dns'); @@ -13,13 +14,13 @@ var methods = [ 'resolveSrv', 'resolveNaptr', 'resolveSoa' -] +]; methods.forEach(function(method) { var d = domain.create(); d.run(function() { dns[method]('google.com', function() { - assert.strictEqual(process.domain, d, method + ' retains domain') + assert.strictEqual(process.domain, d, method + ' retains domain'); }); }); }); diff --git a/test/parallel/test-dns-lookup-cb-error.js b/test/parallel/test-dns-lookup-cb-error.js index 2aa9ffe7d6301f..330dfb5d57092a 100644 --- a/test/parallel/test-dns-lookup-cb-error.js +++ b/test/parallel/test-dns-lookup-cb-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cares = process.binding('cares_wrap'); diff --git a/test/parallel/test-dns-regress-6244.js b/test/parallel/test-dns-regress-6244.js index 8bed54f1b297f5..7ed7a892069870 100644 --- a/test/parallel/test-dns-regress-6244.js +++ b/test/parallel/test-dns-regress-6244.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var dns = require('dns'); diff --git a/test/parallel/test-dns-regress-7070.js b/test/parallel/test-dns-regress-7070.js index 79f0d7d9e0ca00..1fbd7f07a9d520 100644 --- a/test/parallel/test-dns-regress-7070.js +++ b/test/parallel/test-dns-regress-7070.js @@ -1,7 +1,8 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dns = require('dns'); // Should not raise assertion error. Issue #7070 -assert.throws(function () { dns.resolveNs([]); }); // bad name -assert.throws(function () { dns.resolveNs(''); }); // bad callback +assert.throws(function() { dns.resolveNs([]); }); // bad name +assert.throws(function() { dns.resolveNs(''); }); // bad callback diff --git a/test/parallel/test-dns.js b/test/parallel/test-dns.js index 1de9bbfdf77977..abc7edbf598097 100644 --- a/test/parallel/test-dns.js +++ b/test/parallel/test-dns.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -12,16 +13,16 @@ var goog = [ '8.8.8.8', '8.8.4.4', ]; -assert.doesNotThrow(function () { dns.setServers(goog) }); +assert.doesNotThrow(function() { dns.setServers(goog); }); assert.deepEqual(dns.getServers(), goog); -assert.throws(function () { dns.setServers(['foobar']) }); +assert.throws(function() { dns.setServers(['foobar']); }); assert.deepEqual(dns.getServers(), goog); var goog6 = [ '2001:4860:4860::8888', '2001:4860:4860::8844', ]; -assert.doesNotThrow(function () { dns.setServers(goog6) }); +assert.doesNotThrow(function() { dns.setServers(goog6); }); assert.deepEqual(dns.getServers(), goog6); goog6.push('4.4.4.4'); @@ -39,7 +40,7 @@ var portsExpected = [ dns.setServers(ports); assert.deepEqual(dns.getServers(), portsExpected); -assert.doesNotThrow(function () { dns.setServers([]); }); +assert.doesNotThrow(function() { dns.setServers([]); }); assert.deepEqual(dns.getServers(), []); assert.throws(function() { diff --git a/test/parallel/test-domain-abort-on-uncaught.js b/test/parallel/test-domain-abort-on-uncaught.js index e11bbcc6bc755f..f4884aa8f33421 100644 --- a/test/parallel/test-domain-abort-on-uncaught.js +++ b/test/parallel/test-domain-abort-on-uncaught.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --abort_on_uncaught_exception var common = require('../common'); @@ -18,7 +19,7 @@ process.on('exit', function() { assert.equal(errors, tests.length); }); -tests.forEach(function(test) { test(); }) +tests.forEach(function(test) { test(); }); function nextTick() { var d = domain.create(); @@ -84,10 +85,10 @@ function netServer() { conn.pipe(conn); }); server.listen(common.PORT, '0.0.0.0', function() { - var conn = net.connect(common.PORT, '0.0.0.0') + var conn = net.connect(common.PORT, '0.0.0.0'); conn.once('data', function() { throw new Error('ok'); - }) + }); conn.end('ok'); server.close(); }); diff --git a/test/parallel/test-domain-crypto.js b/test/parallel/test-domain-crypto.js index dc183b7bda1760..96047474956e73 100644 --- a/test/parallel/test-domain-crypto.js +++ b/test/parallel/test-domain-crypto.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ try { var crypto = require('crypto'); } catch (e) { diff --git a/test/parallel/test-domain-enter-exit.js b/test/parallel/test-domain-enter-exit.js index 32ec0ca2472c8c..5cf0d9c54a3122 100644 --- a/test/parallel/test-domain-enter-exit.js +++ b/test/parallel/test-domain-enter-exit.js @@ -1,3 +1,4 @@ +'use strict'; // Make sure the domain stack is a stack var assert = require('assert'); @@ -5,7 +6,7 @@ var domain = require('domain'); function names(array) { return array.map(function(d) { - return d.name + return d.name; }).join(', '); } diff --git a/test/parallel/test-domain-exit-dispose-again.js b/test/parallel/test-domain-exit-dispose-again.js index c651181092737b..d7046481d112ea 100644 --- a/test/parallel/test-domain-exit-dispose-again.js +++ b/test/parallel/test-domain-exit-dispose-again.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); @@ -6,7 +7,7 @@ var disposalFailed = false; // no matter what happens, we should increment a 10 times. var a = 0; log(); -function log(){ +function log() { console.log(a++, process.domain); if (a < 10) setTimeout(log, 20); } @@ -16,7 +17,7 @@ var secondTimerRan = false; // in 50ms we'll throw an error. setTimeout(err, 50); setTimeout(secondTimer, 50); -function err(){ +function err() { var d = domain.create(); d.on('error', handle); d.run(err2); diff --git a/test/parallel/test-domain-exit-dispose.js b/test/parallel/test-domain-exit-dispose.js index a01cee5c73cb0c..90e7210ce21aea 100644 --- a/test/parallel/test-domain-exit-dispose.js +++ b/test/parallel/test-domain-exit-dispose.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); @@ -6,14 +7,14 @@ var disposalFailed = false; // no matter what happens, we should increment a 10 times. var a = 0; log(); -function log(){ +function log() { console.log(a++, process.domain); if (a < 10) setTimeout(log, 20); } // in 50ms we'll throw an error. setTimeout(err, 50); -function err(){ +function err() { var d = domain.create(); d.on('error', handle); d.run(err2); diff --git a/test/parallel/test-domain-from-timer.js b/test/parallel/test-domain-from-timer.js index 91dff3875cd7a2..93661b419b0bbf 100644 --- a/test/parallel/test-domain-from-timer.js +++ b/test/parallel/test-domain-from-timer.js @@ -1,3 +1,4 @@ +'use strict'; // Simple tests of most basic domain functionality. var common = require('../common'); @@ -10,7 +11,7 @@ setTimeout(function() { var d = domain.create(); d.run(function() { process.nextTick(function() { - console.trace('in nexttick', process.domain === d) + console.trace('in nexttick', process.domain === d); assert.equal(process.domain, d); }); }); diff --git a/test/parallel/test-domain-http-server.js b/test/parallel/test-domain-http-server.js index 77e10911716fb0..7cabf205e8f51c 100644 --- a/test/parallel/test-domain-http-server.js +++ b/test/parallel/test-domain-http-server.js @@ -1,3 +1,4 @@ +'use strict'; var domain = require('domain'); var http = require('http'); var assert = require('assert'); diff --git a/test/parallel/test-domain-implicit-fs.js b/test/parallel/test-domain-implicit-fs.js index 4a00b9a17ad5db..fd21dcafe0858f 100644 --- a/test/parallel/test-domain-implicit-fs.js +++ b/test/parallel/test-domain-implicit-fs.js @@ -1,3 +1,4 @@ +'use strict'; // Simple tests of most basic domain functionality. var common = require('../common'); diff --git a/test/parallel/test-domain-multi.js b/test/parallel/test-domain-multi.js index 270ecde4962241..e5f9f6748b178e 100644 --- a/test/parallel/test-domain-multi.js +++ b/test/parallel/test-domain-multi.js @@ -1,3 +1,4 @@ +'use strict'; // Tests of multiple domains happening at once. var common = require('../common'); @@ -20,7 +21,7 @@ a.on('error', function(er) { var http = require('http'); -var server = http.createServer(function (req, res) { +var server = http.createServer(function(req, res) { // child domain of a. var b = domain.create(); a.add(b); @@ -31,9 +32,9 @@ var server = http.createServer(function (req, res) { b.add(req); b.add(res); - b.on('error', function (er) { + b.on('error', function(er) { caughtB = true; - console.error('Error encountered', er) + console.error('Error encountered', er); if (res) { res.writeHead(500); res.end('An error occurred'); @@ -52,7 +53,7 @@ var server = http.createServer(function (req, res) { }).listen(common.PORT); var c = domain.create(); -var req = http.get({ host: 'localhost', port: common.PORT }) +var req = http.get({ host: 'localhost', port: common.PORT }); // add the request to the C domain c.add(req); @@ -71,7 +72,7 @@ c.on('error', function(er) { process.on('exit', function() { assert.equal(caughtA, false); - assert.equal(caughtB, true) - assert.equal(caughtC, true) + assert.equal(caughtB, true); + assert.equal(caughtC, true); console.log('ok - Errors went where they were supposed to go'); }); diff --git a/test/parallel/test-domain-nested-throw.js b/test/parallel/test-domain-nested-throw.js index 87039bb3f939ce..0fba3001b543fb 100644 --- a/test/parallel/test-domain-nested-throw.js +++ b/test/parallel/test-domain-nested-throw.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -50,7 +51,7 @@ function throw2() { function inner(throw1, throw2) { var domain1 = domain.createDomain(); - domain1.on('error', function (err) { + domain1.on('error', function(err) { if (gotDomain1Error) { console.error('got domain 1 twice'); process.exit(1); @@ -60,7 +61,7 @@ function inner(throw1, throw2) { throw2(); }); - domain1.run(function () { + domain1.run(function() { throw1(); }); } @@ -68,7 +69,7 @@ function inner(throw1, throw2) { function outer() { var domain2 = domain.createDomain(); - domain2.on('error', function (err) { + domain2.on('error', function(err) { if (gotDomain2Error) { console.error('got domain 2 twice'); process.exit(1); @@ -76,7 +77,7 @@ function outer() { gotDomain2Error = true; }); - domain2.run(function () { + domain2.run(function() { inner(throw1, throw2); }); } diff --git a/test/parallel/test-domain-nested.js b/test/parallel/test-domain-nested.js index 9334c287baedc1..d0ef072339b8f9 100644 --- a/test/parallel/test-domain-nested.js +++ b/test/parallel/test-domain-nested.js @@ -1,3 +1,4 @@ +'use strict'; // Make sure that the nested domains don't cause the domain stack to grow var assert = require('assert'); @@ -10,11 +11,11 @@ process.on('exit', function(c) { domain.create().run(function() { domain.create().run(function() { domain.create().run(function() { - domain.create().on("error", function(e) { + domain.create().on('error', function(e) { // Don't need to do anything here }).run(function() { - throw new Error("died") - }) - }) - }) -}) + throw new Error('died'); + }); + }); + }); +}); diff --git a/test/parallel/test-domain-safe-exit.js b/test/parallel/test-domain-safe-exit.js index 029687411a09b9..6661c577b30c87 100644 --- a/test/parallel/test-domain-safe-exit.js +++ b/test/parallel/test-domain-safe-exit.js @@ -1,3 +1,4 @@ +'use strict'; // Make sure the domain stack doesn't get clobbered by un-matched .exit() var assert = require('assert'); diff --git a/test/parallel/test-domain-stack.js b/test/parallel/test-domain-stack.js index be611a872117ff..f9b5648a6619a7 100644 --- a/test/parallel/test-domain-stack.js +++ b/test/parallel/test-domain-stack.js @@ -1,3 +1,4 @@ +'use strict'; // Make sure that the domain stack doesn't get out of hand. var common = require('../common'); diff --git a/test/parallel/test-domain-timers.js b/test/parallel/test-domain-timers.js index 5a34bc7449a951..7530c9edba40b1 100644 --- a/test/parallel/test-domain-timers.js +++ b/test/parallel/test-domain-timers.js @@ -1,3 +1,4 @@ +'use strict'; var domain = require('domain'); var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-domain.js b/test/parallel/test-domain.js index a3f7b76848a581..9cca05178ef10f 100644 --- a/test/parallel/test-domain.js +++ b/test/parallel/test-domain.js @@ -1,3 +1,4 @@ +'use strict'; // Simple tests of most basic domain functionality. var common = require('../common'); @@ -15,7 +16,7 @@ d.on('error', function(er) { console.error('caught', er && (er.message || er)); var er_message = er.message; - var er_path = er.path + var er_path = er.path; // On windows, error messages can contain full path names. If this is the // case, remove the directory part. @@ -58,7 +59,8 @@ d.on('error', function(er) { assert.equal(typeof er.errno, 'number'); break; - case "ENOENT: no such file or directory, open 'stream for nonexistent file'": + case + "ENOENT: no such file or directory, open 'stream for nonexistent file'": assert.equal(typeof er.errno, 'number'); assert.equal(er.code, 'ENOENT'); assert.equal(er_path, 'stream for nonexistent file'); @@ -129,7 +131,7 @@ expectCaught++; // set up while in the scope of the d domain. d.run(function() { process.nextTick(function() { - var i = setInterval(function () { + var i = setInterval(function() { clearInterval(i); setTimeout(function() { fs.stat('this file does not exist', function(er, stat) { @@ -178,7 +180,7 @@ expectCaught++; // intercepted should never pass first argument to callback function fn2(data) { - assert.equal(data, 'data', 'should not be null err argument') + assert.equal(data, 'data', 'should not be null err argument'); } var bound = d.intercept(fn2); @@ -220,7 +222,7 @@ expectCaught++; var implicit; d.run(function() { - implicit = new events.EventEmitter; + implicit = new events.EventEmitter(); }); setTimeout(function() { @@ -230,24 +232,24 @@ setTimeout(function() { expectCaught++; -var result = d.run(function () { +var result = d.run(function() { return 'return value'; }); assert.equal(result, 'return value'); // check if the executed function take in count the applied parameters -result = d.run(function (a, b) { +result = d.run(function(a, b) { return a + ' ' + b; }, 'return', 'value'); assert.equal(result, 'return value'); -var fst = fs.createReadStream('stream for nonexistent file') -d.add(fst) +var fst = fs.createReadStream('stream for nonexistent file'); +d.add(fst); expectCaught++; -[42, null, , false, function(){}, 'string'].forEach(function(something) { +[42, null, , false, function() {}, 'string'].forEach(function(something) { var d = new domain.Domain(); d.run(function() { process.nextTick(function() { diff --git a/test/parallel/test-error-reporting.js b/test/parallel/test-error-reporting.js index 9caabe0d6160e2..0b5c7652871138 100644 --- a/test/parallel/test-error-reporting.js +++ b/test/parallel/test-error-reporting.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; diff --git a/test/parallel/test-eval-require.js b/test/parallel/test-eval-require.js index eeaa624b396ab7..f966b5a98c80ba 100644 --- a/test/parallel/test-eval-require.js +++ b/test/parallel/test-eval-require.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-eval.js b/test/parallel/test-eval.js index e504ceca12678c..d3a83fbd5a7060 100644 --- a/test/parallel/test-eval.js +++ b/test/parallel/test-eval.js @@ -1,3 +1,4 @@ +'use strict'; require('../common'); var util = require('util'); var assert = require('assert'); diff --git a/test/parallel/test-event-emitter-add-listeners.js b/test/parallel/test-event-emitter-add-listeners.js index 7cc302e0b81695..cc30fd24add340 100644 --- a/test/parallel/test-event-emitter-add-listeners.js +++ b/test/parallel/test-event-emitter-add-listeners.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); @@ -53,7 +54,7 @@ process.on('exit', function() { var listen1 = function listen1() {}; var listen2 = function listen2() {}; -var e1 = new events.EventEmitter; +var e1 = new events.EventEmitter(); e1.once('newListener', function() { assert.deepEqual(e1.listeners('hello'), []); e1.once('newListener', function() { diff --git a/test/parallel/test-event-emitter-check-listener-leaks.js b/test/parallel/test-event-emitter-check-listener-leaks.js index 25e53d2c6a188f..90f686b5422c43 100644 --- a/test/parallel/test-event-emitter-check-listener-leaks.js +++ b/test/parallel/test-event-emitter-check-listener-leaks.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); diff --git a/test/parallel/test-event-emitter-errors.js b/test/parallel/test-event-emitter-errors.js new file mode 100644 index 00000000000000..49203961ac8d9a --- /dev/null +++ b/test/parallel/test-event-emitter-errors.js @@ -0,0 +1,9 @@ +'use strict'; +var EventEmitter = require('events'); +var assert = require('assert'); + +var EE = new EventEmitter(); + +assert.throws(function() { + EE.emit('error', 'Accepts a string'); +}, /Accepts a string/); diff --git a/test/parallel/test-event-emitter-get-max-listeners.js b/test/parallel/test-event-emitter-get-max-listeners.js index 57430a4e9bec37..0cad09fdb8b8ef 100644 --- a/test/parallel/test-event-emitter-get-max-listeners.js +++ b/test/parallel/test-event-emitter-get-max-listeners.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var EventEmitter = require('events'); diff --git a/test/parallel/test-event-emitter-listeners-side-effects.js b/test/parallel/test-event-emitter-listeners-side-effects.js index 46eedf812d2b0e..de541c535ef0ed 100644 --- a/test/parallel/test-event-emitter-listeners-side-effects.js +++ b/test/parallel/test-event-emitter-listeners-side-effects.js @@ -1,3 +1,4 @@ +'use strict'; // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); @@ -7,7 +8,7 @@ var events = require('events'); var EventEmitter = require('events').EventEmitter; var assert = require('assert'); -var e = new EventEmitter; +var e = new EventEmitter(); var fl; // foo listeners fl = e.listeners('foo'); diff --git a/test/parallel/test-event-emitter-listeners.js b/test/parallel/test-event-emitter-listeners.js index 6baad62968f549..be6b83856249b4 100644 --- a/test/parallel/test-event-emitter-listeners.js +++ b/test/parallel/test-event-emitter-listeners.js @@ -1,3 +1,4 @@ +'use strict'; // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); diff --git a/test/parallel/test-event-emitter-max-listeners.js b/test/parallel/test-event-emitter-max-listeners.js index cea5fbf022ea2c..5e754698d0a018 100644 --- a/test/parallel/test-event-emitter-max-listeners.js +++ b/test/parallel/test-event-emitter-max-listeners.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); @@ -26,7 +27,7 @@ assert.throws(function() { }); assert.throws(function() { - e.setMaxListeners("and even this"); + e.setMaxListeners('and even this'); }); e.emit('maxListeners'); diff --git a/test/parallel/test-event-emitter-method-names.js b/test/parallel/test-event-emitter-method-names.js index 27061df4e4a66d..a260aa779855aa 100644 --- a/test/parallel/test-event-emitter-method-names.js +++ b/test/parallel/test-event-emitter-method-names.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); diff --git a/test/parallel/test-event-emitter-modify-in-emit.js b/test/parallel/test-event-emitter-modify-in-emit.js index 3b05a88a3e00a6..85845cc4443b32 100644 --- a/test/parallel/test-event-emitter-modify-in-emit.js +++ b/test/parallel/test-event-emitter-modify-in-emit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); diff --git a/test/parallel/test-event-emitter-no-error-provided-to-error-event.js b/test/parallel/test-event-emitter-no-error-provided-to-error-event.js index 5c50c32d489b24..e85361475f894e 100644 --- a/test/parallel/test-event-emitter-no-error-provided-to-error-event.js +++ b/test/parallel/test-event-emitter-no-error-provided-to-error-event.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); @@ -9,13 +10,13 @@ var e = new events.EventEmitter(); var d = domain.create(); d.add(e); -d.on('error', function (er) { +d.on('error', function(er) { assert(er instanceof Error, 'error created'); errorCatched = true; }); e.emit('error'); -process.on('exit', function () { +process.on('exit', function() { assert(errorCatched, 'error got caught'); }); diff --git a/test/parallel/test-event-emitter-num-args.js b/test/parallel/test-event-emitter-num-args.js index 20c003f3303a35..522fb2e2175d81 100644 --- a/test/parallel/test-event-emitter-num-args.js +++ b/test/parallel/test-event-emitter-num-args.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); diff --git a/test/parallel/test-event-emitter-once.js b/test/parallel/test-event-emitter-once.js index c5cd007ea265da..1085e7942a59bf 100644 --- a/test/parallel/test-event-emitter-once.js +++ b/test/parallel/test-event-emitter-once.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); @@ -29,12 +30,12 @@ process.on('exit', function() { var times_recurse_emitted = 0; e.once('e', function() { - e.emit('e'); - times_recurse_emitted++; + e.emit('e'); + times_recurse_emitted++; }); e.once('e', function() { - times_recurse_emitted++; + times_recurse_emitted++; }); e.emit('e'); diff --git a/test/parallel/test-event-emitter-remove-all-listeners.js b/test/parallel/test-event-emitter-remove-all-listeners.js index 8c6d68ec5fa2ee..54dedfa1362d29 100644 --- a/test/parallel/test-event-emitter-remove-all-listeners.js +++ b/test/parallel/test-event-emitter-remove-all-listeners.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); @@ -9,7 +10,7 @@ function expect(expected) { assert.deepEqual(actual.sort(), expected.sort()); }); function listener(name) { - actual.push(name) + actual.push(name); } return common.mustCall(listener, expected.length); } @@ -63,9 +64,9 @@ var expectLength = 2; e4.on('removeListener', function(name, listener) { assert.equal(expectLength--, this.listeners('baz').length); }); -e4.on('baz', function(){}); -e4.on('baz', function(){}); -e4.on('baz', function(){}); -assert.equal(e4.listeners('baz').length, expectLength+1); +e4.on('baz', function() {}); +e4.on('baz', function() {}); +e4.on('baz', function() {}); +assert.equal(e4.listeners('baz').length, expectLength + 1); e4.removeAllListeners('baz'); assert.equal(e4.listeners('baz').length, 0); diff --git a/test/parallel/test-event-emitter-remove-listeners.js b/test/parallel/test-event-emitter-remove-listeners.js index 5d8acafc063d09..409ccbebe25b86 100644 --- a/test/parallel/test-event-emitter-remove-listeners.js +++ b/test/parallel/test-event-emitter-remove-listeners.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); diff --git a/test/parallel/test-event-emitter-set-max-listeners-side-effects.js b/test/parallel/test-event-emitter-set-max-listeners-side-effects.js index d4842c395ee062..f09f130ab489ed 100644 --- a/test/parallel/test-event-emitter-set-max-listeners-side-effects.js +++ b/test/parallel/test-event-emitter-set-max-listeners-side-effects.js @@ -1,8 +1,9 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); -var e = new events.EventEmitter; +var e = new events.EventEmitter(); assert.deepEqual(e._events, {}); e.setMaxListeners(5); diff --git a/test/parallel/test-event-emitter-subclass.js b/test/parallel/test-event-emitter-subclass.js index d4be78481238ba..327738271184b0 100644 --- a/test/parallel/test-event-emitter-subclass.js +++ b/test/parallel/test-event-emitter-subclass.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var EventEmitter = require('events').EventEmitter; @@ -43,6 +44,6 @@ MyEE2.prototype = new EventEmitter(); var ee1 = new MyEE2(); var ee2 = new MyEE2(); -ee1.on('x', function () {}); +ee1.on('x', function() {}); assert.equal(EventEmitter.listenerCount(ee2, 'x'), 0); diff --git a/test/parallel/test-exception-handler.js b/test/parallel/test-exception-handler.js index 4a781a0a9cd074..9cc8106ea6f80a 100644 --- a/test/parallel/test-exception-handler.js +++ b/test/parallel/test-exception-handler.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-exception-handler2.js b/test/parallel/test-exception-handler2.js index 77f3eb1d5cfd77..58e84ad21ba4ee 100644 --- a/test/parallel/test-exception-handler2.js +++ b/test/parallel/test-exception-handler2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-exec-max-buffer.js b/test/parallel/test-exec-max-buffer.js index a5a24eabeae7cb..5cae35b69f95d5 100644 --- a/test/parallel/test-exec-max-buffer.js +++ b/test/parallel/test-exec-max-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var exec = require('child_process').exec; var assert = require('assert'); diff --git a/test/parallel/test-file-read-noexist.js b/test/parallel/test-file-read-noexist.js index ad8dd5dc664921..47c8d256e3ba18 100644 --- a/test/parallel/test-file-read-noexist.js +++ b/test/parallel/test-file-read-noexist.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-file-write-stream.js b/test/parallel/test-file-write-stream.js index 9f0d66a84f722e..7882d2370d99c9 100644 --- a/test/parallel/test-file-write-stream.js +++ b/test/parallel/test-file-write-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-file-write-stream2.js b/test/parallel/test-file-write-stream2.js index 049d7d25e1c029..2563b1a300f526 100644 --- a/test/parallel/test-file-write-stream2.js +++ b/test/parallel/test-file-write-stream2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-file-write-stream3.js b/test/parallel/test-file-write-stream3.js index 2acb7053042c87..7223bd43f5230b 100644 --- a/test/parallel/test-file-write-stream3.js +++ b/test/parallel/test-file-write-stream3.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-fs-access.js b/test/parallel/test-fs-access.js index 1c9773867ca706..6ad28612e9bb1b 100644 --- a/test/parallel/test-fs-access.js +++ b/test/parallel/test-fs-access.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -20,8 +21,8 @@ var createFileWithPerms = function(file, mode) { fs.chmodSync(file, mode); }; -createFileWithPerms(readOnlyFile, 0444); -createFileWithPerms(readWriteFile, 0666); +createFileWithPerms(readOnlyFile, 0o444); +createFileWithPerms(readWriteFile, 0o666); /* * On non-Windows supported platforms, fs.access(readOnlyFile, W_OK, ...) @@ -112,7 +113,7 @@ assert.doesNotThrow(function() { assert.throws(function() { fs.accessSync(doesNotExist); -}, function (err) { +}, function(err) { return err.code === 'ENOENT' && err.path === doesNotExist; }); diff --git a/test/parallel/test-fs-append-file-sync.js b/test/parallel/test-fs-append-file-sync.js index 72cfdf75e23b27..5a38014399dd5f 100644 --- a/test/parallel/test-fs-append-file-sync.js +++ b/test/parallel/test-fs-append-file-sync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var join = require('path').join; @@ -55,13 +56,13 @@ var filename4 = join(common.tmpDir, 'append-sync4.txt'); fs.writeFileSync(filename4, currentFileData, { mode: m }); common.error('appending to ' + filename4); -var m = 0600; +var m = 0o600; fs.appendFileSync(filename4, num, { mode: m }); // windows permissions aren't unix if (process.platform !== 'win32') { var st = fs.statSync(filename4); - assert.equal(st.mode & 0700, m); + assert.equal(st.mode & 0o700, m); } var fileData4 = fs.readFileSync(filename4); diff --git a/test/parallel/test-fs-append-file.js b/test/parallel/test-fs-append-file.js index ba2d34e5a1f0a6..4cd75ccacc60d8 100644 --- a/test/parallel/test-fs-append-file.js +++ b/test/parallel/test-fs-append-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -80,7 +81,7 @@ fs.writeFileSync(filename4, currentFileData); common.error('appending to ' + filename4); -var m = 0600; +var m = 0o600; fs.appendFile(filename4, n, { mode: m }, function(e) { if (e) throw e; @@ -90,7 +91,7 @@ fs.appendFile(filename4, n, { mode: m }, function(e) { // windows permissions aren't unix if (process.platform !== 'win32') { var st = fs.statSync(filename4); - assert.equal(st.mode & 0700, m); + assert.equal(st.mode & 0o700, m); } fs.readFile(filename4, function(e, buffer) { diff --git a/test/parallel/test-fs-chmod.js b/test/parallel/test-fs-chmod.js index 55056125da980d..a9d694adeccc01 100644 --- a/test/parallel/test-fs-chmod.js +++ b/test/parallel/test-fs-chmod.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -44,11 +45,11 @@ function closeSync() { // On Windows chmod is only able to manipulate read-only bit if (is_windows) { - mode_async = 0400; // read-only - mode_sync = 0600; // read-write + mode_async = 0o400; // read-only + mode_sync = 0o600; // read-write } else { - mode_async = 0777; - mode_sync = 0644; + mode_async = 0o777; + mode_sync = 0o644; } var file1 = path.join(common.fixturesDir, 'a.js'), @@ -61,16 +62,16 @@ fs.chmod(file1, mode_async.toString(8), function(err) { console.log(fs.statSync(file1).mode); if (is_windows) { - assert.ok((fs.statSync(file1).mode & 0777) & mode_async); + assert.ok((fs.statSync(file1).mode & 0o777) & mode_async); } else { - assert.equal(mode_async, fs.statSync(file1).mode & 0777); + assert.equal(mode_async, fs.statSync(file1).mode & 0o777); } fs.chmodSync(file1, mode_sync); if (is_windows) { - assert.ok((fs.statSync(file1).mode & 0777) & mode_sync); + assert.ok((fs.statSync(file1).mode & 0o777) & mode_sync); } else { - assert.equal(mode_sync, fs.statSync(file1).mode & 0777); + assert.equal(mode_sync, fs.statSync(file1).mode & 0o777); } success_count++; } @@ -89,16 +90,16 @@ fs.open(file2, 'a', function(err, fd) { console.log(fs.fstatSync(fd).mode); if (is_windows) { - assert.ok((fs.fstatSync(fd).mode & 0777) & mode_async); + assert.ok((fs.fstatSync(fd).mode & 0o777) & mode_async); } else { - assert.equal(mode_async, fs.fstatSync(fd).mode & 0777); + assert.equal(mode_async, fs.fstatSync(fd).mode & 0o777); } fs.fchmodSync(fd, mode_sync); if (is_windows) { - assert.ok((fs.fstatSync(fd).mode & 0777) & mode_sync); + assert.ok((fs.fstatSync(fd).mode & 0o777) & mode_sync); } else { - assert.equal(mode_sync, fs.fstatSync(fd).mode & 0777); + assert.equal(mode_sync, fs.fstatSync(fd).mode & 0o777); } success_count++; fs.close(fd); @@ -120,10 +121,10 @@ if (fs.lchmod) { got_error = true; } else { console.log(fs.lstatSync(link).mode); - assert.equal(mode_async, fs.lstatSync(link).mode & 0777); + assert.equal(mode_async, fs.lstatSync(link).mode & 0o777); fs.lchmodSync(link, mode_sync); - assert.equal(mode_sync, fs.lstatSync(link).mode & 0777); + assert.equal(mode_sync, fs.lstatSync(link).mode & 0o777); success_count++; } }); diff --git a/test/parallel/test-fs-empty-readStream.js b/test/parallel/test-fs-empty-readStream.js index 0c470076da7df1..0863e0cdba4ddb 100644 --- a/test/parallel/test-fs-empty-readStream.js +++ b/test/parallel/test-fs-empty-readStream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -5,43 +6,43 @@ var fs = require('fs'); var emptyFile = path.join(common.fixturesDir, 'empty.txt'); -fs.open(emptyFile, 'r', function (error, fd) { +fs.open(emptyFile, 'r', function(error, fd) { assert.ifError(error); var read = fs.createReadStream(emptyFile, { 'fd': fd }); - read.once('data', function () { + read.once('data', function() { throw new Error('data event should not emit'); }); var readEmit = false; - read.once('end', function () { + read.once('end', function() { readEmit = true; console.error('end event 1'); }); - setTimeout(function () { + setTimeout(function() { assert.equal(readEmit, true); }, common.platformTimeout(50)); }); -fs.open(emptyFile, 'r', function (error, fd) { +fs.open(emptyFile, 'r', function(error, fd) { assert.ifError(error); var read = fs.createReadStream(emptyFile, { 'fd': fd }); read.pause(); - read.once('data', function () { + read.once('data', function() { throw new Error('data event should not emit'); }); var readEmit = false; - read.once('end', function () { + read.once('end', function() { readEmit = true; console.error('end event 2'); }); - setTimeout(function () { + setTimeout(function() { assert.equal(readEmit, false); }, common.platformTimeout(50)); }); diff --git a/test/parallel/test-fs-error-messages.js b/test/parallel/test-fs-error-messages.js index e174e1c023ff21..ca0684c1d71363 100644 --- a/test/parallel/test-fs-error-messages.js +++ b/test/parallel/test-fs-error-messages.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -55,7 +56,7 @@ fs.rmdir(fn, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); -fs.mkdir(existingFile, 0666, function(err) { +fs.mkdir(existingFile, 0o666, function(err) { assert.ok(0 <= err.message.indexOf(existingFile)); }); @@ -63,11 +64,11 @@ fs.rmdir(existingFile, function(err) { assert.ok(0 <= err.message.indexOf(existingFile)); }); -fs.chmod(fn, 0666, function(err) { +fs.chmod(fn, 0o666, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); -fs.open(fn, 'r', 0666, function(err) { +fs.open(fn, 'r', 0o666, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); @@ -90,7 +91,7 @@ try { try { ++expected; - fs.mkdirSync(existingFile, 0666); + fs.mkdirSync(existingFile, 0o666); } catch (err) { errors.push('mkdir'); assert.ok(0 <= err.message.indexOf(existingFile)); @@ -98,7 +99,7 @@ try { try { ++expected; - fs.chmodSync(fn, 0666); + fs.chmodSync(fn, 0o666); } catch (err) { errors.push('chmod'); assert.ok(0 <= err.message.indexOf(fn)); diff --git a/test/parallel/test-fs-exists.js b/test/parallel/test-fs-exists.js index 4eb14e1e3bc73f..fcbd729a5ed850 100644 --- a/test/parallel/test-fs-exists.js +++ b/test/parallel/test-fs-exists.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-fsync.js b/test/parallel/test-fs-fsync.js index 50c010a49a5b1b..661a73baefad77 100644 --- a/test/parallel/test-fs-fsync.js +++ b/test/parallel/test-fs-fsync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -9,7 +10,7 @@ var file = path.join(common.fixturesDir, 'a.js'); common.error('open ' + file); -fs.open(file, 'a', 0777, function(err, fd) { +fs.open(file, 'a', 0o777, function(err, fd) { common.error('fd ' + fd); if (err) throw err; diff --git a/test/parallel/test-fs-long-path.js b/test/parallel/test-fs-long-path.js index ae8a5669f8193e..158ba04f49df08 100644 --- a/test/parallel/test-fs-long-path.js +++ b/test/parallel/test-fs-long-path.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var fs = require('fs'); var path = require('path'); diff --git a/test/parallel/test-fs-make-callback.js b/test/parallel/test-fs-make-callback.js index 91990015b8220c..a15a16404df003 100644 --- a/test/parallel/test-fs-make-callback.js +++ b/test/parallel/test-fs-make-callback.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-mkdir.js b/test/parallel/test-fs-mkdir.js index b8a688adc4c736..b5451d20576aac 100644 --- a/test/parallel/test-fs-mkdir.js +++ b/test/parallel/test-fs-mkdir.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-null-bytes.js b/test/parallel/test-fs-null-bytes.js index 4d1dcb3972a7ba..77228521e6fc9d 100644 --- a/test/parallel/test-fs-null-bytes.js +++ b/test/parallel/test-fs-null-bytes.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-open-flags.js b/test/parallel/test-fs-open-flags.js index bf4619d19d4f33..c7d53117d587fc 100644 --- a/test/parallel/test-fs-open-flags.js +++ b/test/parallel/test-fs-open-flags.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-fs-open.js b/test/parallel/test-fs-open.js index ea099d2e14c89f..59b605841b4440 100644 --- a/test/parallel/test-fs-open.js +++ b/test/parallel/test-fs-open.js @@ -1,3 +1,4 @@ +'use strict'; var constants = require('constants'); var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-fs-read-buffer.js b/test/parallel/test-fs-read-buffer.js index 0dc7a851da3c73..57a28d477c6575 100644 --- a/test/parallel/test-fs-read-buffer.js +++ b/test/parallel/test-fs-read-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'), diff --git a/test/parallel/test-fs-read-file-sync-hostname.js b/test/parallel/test-fs-read-file-sync-hostname.js index a2c8ac5da7ce61..c5c5264c0dde3b 100644 --- a/test/parallel/test-fs-read-file-sync-hostname.js +++ b/test/parallel/test-fs-read-file-sync-hostname.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-read-file-sync.js b/test/parallel/test-fs-read-file-sync.js index cf6ab72dbf5b77..d34bf7748cea89 100644 --- a/test/parallel/test-fs-read-file-sync.js +++ b/test/parallel/test-fs-read-file-sync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-read-stream-err.js b/test/parallel/test-fs-read-stream-err.js index a3d1457e610f7b..1eb6aa57906b05 100644 --- a/test/parallel/test-fs-read-stream-err.js +++ b/test/parallel/test-fs-read-stream-err.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-read-stream-fd-leak.js b/test/parallel/test-fs-read-stream-fd-leak.js index abd954506b19d4..ddbccda1b8bea3 100644 --- a/test/parallel/test-fs-read-stream-fd-leak.js +++ b/test/parallel/test-fs-read-stream-fd-leak.js @@ -1,3 +1,4 @@ +'use strict'; // Copyright io.js contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -34,12 +35,12 @@ var emptyTxt = path.join(common.fixturesDir, 'empty.txt'); fs.open = function() { openCount++; return _fsopen.apply(null, arguments); -} +}; fs.close = function() { openCount--; return _fsclose.apply(null, arguments); -} +}; function testLeak(endFn, callback) { console.log('testing for leaks from fs.createReadStream().%s()...', endFn); @@ -53,7 +54,8 @@ function testLeak(endFn, callback) { if (++i === loopCount) { clearTimeout(this); setTimeout(function() { - assert.equal(0, openCount, 'no leaked file descriptors using ' + endFn + '() (got ' + openCount + ')'); + assert.equal(0, openCount, 'no leaked file descriptors using ' + + endFn + '() (got ' + openCount + ')'); openCount = 0; callback && setTimeout(callback, 100); }, 100); diff --git a/test/parallel/test-fs-read-stream-fd.js b/test/parallel/test-fs-read-stream-fd.js index f57499ca397660..450c56eb8a96b8 100644 --- a/test/parallel/test-fs-read-stream-fd.js +++ b/test/parallel/test-fs-read-stream-fd.js @@ -1,3 +1,4 @@ +'use strict'; var fs = require('fs'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-read-stream-inherit.js b/test/parallel/test-fs-read-stream-inherit.js index c8da148e0486cd..3b53578397f96e 100644 --- a/test/parallel/test-fs-read-stream-inherit.js +++ b/test/parallel/test-fs-read-stream-inherit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -80,7 +81,8 @@ process.on('exit', function() { console.error('ok'); }); -var file4 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1, start: 1, end: 2})); +var file4 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1, + start: 1, end: 2})); assert.equal(file4.start, 1); assert.equal(file4.end, 2); var contentRead = ''; @@ -91,7 +93,8 @@ file4.on('end', function(data) { assert.equal(contentRead, 'yz'); }); -var file5 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1, start: 1})); +var file5 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1, + start: 1})); assert.equal(file5.start, 1); file5.data = ''; file5.on('data', function(data) { @@ -102,7 +105,8 @@ file5.on('end', function() { }); // https://github.com/joyent/node/issues/2320 -var file6 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1.23, start: 1})); +var file6 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1.23, + start: 1})); assert.equal(file6.start, 1); file6.data = ''; file6.on('data', function(data) { @@ -116,7 +120,8 @@ assert.throws(function() { fs.createReadStream(rangeFile, Object.create({start: 10, end: 2})); }, /start must be <= end/); -var stream = fs.createReadStream(rangeFile, Object.create({ start: 0, end: 0 })); +var stream = fs.createReadStream(rangeFile, Object.create({ start: 0, + end: 0 })); assert.equal(stream.start, 0); assert.equal(stream.end, 0); stream.data = ''; @@ -145,7 +150,7 @@ file7.on('end', function() { }); }); -function file7Next(){ +function file7Next() { // This will tell us if the fd is usable again or not. file7 = fs.createReadStream(null, Object.create({fd: file7.fd, start: 0 })); file7.data = ''; @@ -158,7 +163,8 @@ function file7Next(){ } // Just to make sure autoClose won't close the stream because of error. -var file8 = fs.createReadStream(null, Object.create({fd: 13337, autoClose: false })); +var file8 = fs.createReadStream(null, Object.create({fd: 13337, + autoClose: false })); file8.on('data', function() {}); file8.on('error', common.mustCall(function() {})); diff --git a/test/parallel/test-fs-read-stream-resume.js b/test/parallel/test-fs-read-stream-resume.js index c3c61c88cb1f64..9a2e2ee76f78bc 100644 --- a/test/parallel/test-fs-read-stream-resume.js +++ b/test/parallel/test-fs-read-stream-resume.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-fs-read-stream.js b/test/parallel/test-fs-read-stream.js index 85032d49640cdd..490ae0866d9aa0 100644 --- a/test/parallel/test-fs-read-stream.js +++ b/test/parallel/test-fs-read-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -138,7 +139,7 @@ file7.on('end', function() { }); }); -function file7Next(){ +function file7Next() { // This will tell us if the fd is usable again or not. file7 = fs.createReadStream(null, {fd: file7.fd, start: 0 }); file7.data = ''; diff --git a/test/parallel/test-fs-read.js b/test/parallel/test-fs-read.js index 3182733d115251..8b0b6fe0a3844d 100644 --- a/test/parallel/test-fs-read.js +++ b/test/parallel/test-fs-read.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'), diff --git a/test/parallel/test-fs-readfile-empty.js b/test/parallel/test-fs-readfile-empty.js index bf7da45fca93cc..2669ce1ad6b121 100644 --- a/test/parallel/test-fs-readfile-empty.js +++ b/test/parallel/test-fs-readfile-empty.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-fs-readfile-error.js b/test/parallel/test-fs-readfile-error.js index bfe79ab80edb63..6d86ba1a7ec0f1 100644 --- a/test/parallel/test-fs-readfile-error.js +++ b/test/parallel/test-fs-readfile-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; diff --git a/test/parallel/test-fs-readfile-pipe-large.js b/test/parallel/test-fs-readfile-pipe-large.js index 3502cdd5f48778..b25073061002a1 100644 --- a/test/parallel/test-fs-readfile-pipe-large.js +++ b/test/parallel/test-fs-readfile-pipe-large.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-readfile-pipe.js b/test/parallel/test-fs-readfile-pipe.js index da0cd2952fdb05..b55bfb6a22ccd2 100644 --- a/test/parallel/test-fs-readfile-pipe.js +++ b/test/parallel/test-fs-readfile-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-fs-readfile-unlink.js b/test/parallel/test-fs-readfile-unlink.js index bdcf23380e4775..15491b71c433ed 100644 --- a/test/parallel/test-fs-readfile-unlink.js +++ b/test/parallel/test-fs-readfile-unlink.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'), common = require('../common'), fs = require('fs'), diff --git a/test/parallel/test-fs-readfile-zero-byte-liar.js b/test/parallel/test-fs-readfile-zero-byte-liar.js index 532459305c5d91..2c9c6e3db9a584 100644 --- a/test/parallel/test-fs-readfile-zero-byte-liar.js +++ b/test/parallel/test-fs-readfile-zero-byte-liar.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -26,12 +27,12 @@ var d = fs.readFileSync(__filename, 'utf8'); assert.equal(d, dataExpected); var called = false; -fs.readFile(__filename, 'utf8', function (er, d) { +fs.readFile(__filename, 'utf8', function(er, d) { assert.equal(d, dataExpected); called = true; }); process.on('exit', function() { assert(called); - console.log("ok"); + console.log('ok'); }); diff --git a/test/parallel/test-fs-readfilesync-pipe-large.js b/test/parallel/test-fs-readfilesync-pipe-large.js index e62d541a68053c..78dbc31bea9911 100644 --- a/test/parallel/test-fs-readfilesync-pipe-large.js +++ b/test/parallel/test-fs-readfilesync-pipe-large.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-realpath.js b/test/parallel/test-fs-realpath.js index f8299d8d05662b..f0f6d4499c49e0 100644 --- a/test/parallel/test-fs-realpath.js +++ b/test/parallel/test-fs-realpath.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -38,7 +39,7 @@ function tmp(p) { var fixturesAbsDir = common.fixturesDir; var tmpAbsDir = common.tmpDir; -console.error("absolutes\n%s\n%s", fixturesAbsDir, tmpAbsDir); +console.error('absolutes\n%s\n%s', fixturesAbsDir, tmpAbsDir); function asynctest(testBlock, args, callback, assertBlock) { async_expected++; @@ -235,7 +236,7 @@ function test_cyclic_link_overprotection(callback) { var link = folder + '/cycles'; var testPath = cycles; for (var i = 0; i < 10; i++) testPath += '/folder/cycles'; - try {fs.unlinkSync(link)} catch (ex) {} + try {fs.unlinkSync(link);} catch (ex) {} fs.symlinkSync(cycles, link, 'dir'); unlink.push(link); assert.equal(fs.realpathSync(testPath), path.resolve(expected)); @@ -311,7 +312,7 @@ function test_deep_symlink_mix(callback) { var entry = tmp('node-test-realpath-f1'); try { fs.unlinkSync(tmp('node-test-realpath-d2/foo')); } catch (e) {} try { fs.rmdirSync(tmp('node-test-realpath-d2')); } catch (e) {} - fs.mkdirSync(tmp('node-test-realpath-d2'), 0700); + fs.mkdirSync(tmp('node-test-realpath-d2'), 0o700); try { [ [entry, '../' + common.tmpDirName + '/node-test-realpath-d1/foo'], @@ -369,12 +370,14 @@ function test_escape_cwd(cb) { console.log('test_escape_cwd'); asynctest(fs.realpath, ['..'], cb, function(er, uponeActual) { assert.equal(upone, uponeActual, - 'realpath("..") expected: ' + path.resolve(upone) + ' actual:' + uponeActual); + 'realpath("..") expected: ' + path.resolve(upone) + + ' actual:' + uponeActual); }); } var uponeActual = fs.realpathSync('..'); assert.equal(upone, uponeActual, - 'realpathSync("..") expected: ' + path.resolve(upone) + ' actual:' + uponeActual); + 'realpathSync("..") expected: ' + path.resolve(upone) + + ' actual:' + uponeActual); // going up with .. multiple times @@ -394,15 +397,15 @@ function test_up_multiple(cb) { ['a/b', 'a' ].forEach(function(folder) { - try {fs.rmdirSync(tmp(folder))} catch (ex) {} + try {fs.rmdirSync(tmp(folder));} catch (ex) {} }); } function setup() { cleanup(); } setup(); - fs.mkdirSync(tmp('a'), 0755); - fs.mkdirSync(tmp('a/b'), 0755); + fs.mkdirSync(tmp('a'), 0o755); + fs.mkdirSync(tmp('a/b'), 0o755); fs.symlinkSync('..', tmp('a/d'), 'dir'); unlink.push(tmp('a/d')); fs.symlinkSync('..', tmp('a/b/e'), 'dir'); @@ -416,10 +419,10 @@ function test_up_multiple(cb) { assert.equal(fs.realpathSync(abedabeda), abedabeda_real); assert.equal(fs.realpathSync(abedabed), abedabed_real); - fs.realpath(abedabeda, function (er, real) { + fs.realpath(abedabeda, function(er, real) { if (er) throw er; assert.equal(abedabeda_real, real); - fs.realpath(abedabed, function (er, real) { + fs.realpath(abedabed, function(er, real) { if (er) throw er; assert.equal(abedabed_real, real); cb(); @@ -451,14 +454,14 @@ function test_abs_with_kids(cb) { ['/a/b/c/x.txt', '/a/link' ].forEach(function(file) { - try {fs.unlinkSync(root + file)} catch (ex) {} + try {fs.unlinkSync(root + file);} catch (ex) {} }); ['/a/b/c', '/a/b', '/a', '' ].forEach(function(folder) { - try {fs.rmdirSync(root + folder)} catch (ex) {} + try {fs.rmdirSync(root + folder);} catch (ex) {} }); } function setup() { @@ -469,7 +472,7 @@ function test_abs_with_kids(cb) { '/a/b/c' ].forEach(function(folder) { console.log('mkdir ' + root + folder); - fs.mkdirSync(root + folder, 0700); + fs.mkdirSync(root + folder, 0o700); }); fs.writeFileSync(root + '/a/b/c/x.txt', 'foo'); fs.symlinkSync(root + '/a/b', root + '/a/link', type); @@ -575,7 +578,7 @@ function runTest() { var s; try { s = fs.statSync(t); } catch (ex) {} if (s) return; - fs.mkdirSync(t, 0700); + fs.mkdirSync(t, 0o700); }); fs.writeFileSync(tmp('cycles/root.js'), "console.error('roooot!');"); console.error('start tests'); diff --git a/test/parallel/test-fs-sir-writes-alot.js b/test/parallel/test-fs-sir-writes-alot.js index 9df95a77bdfedd..537e94b0acaa3d 100644 --- a/test/parallel/test-fs-sir-writes-alot.js +++ b/test/parallel/test-fs-sir-writes-alot.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var fs = require('fs'); var assert = require('assert'); diff --git a/test/parallel/test-fs-stat.js b/test/parallel/test-fs-stat.js index 88a965974d05ce..123d6608b4bb4f 100644 --- a/test/parallel/test-fs-stat.js +++ b/test/parallel/test-fs-stat.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-stream-double-close.js b/test/parallel/test-fs-stream-double-close.js index 5d772da4aac887..47d129c042b4ad 100644 --- a/test/parallel/test-fs-stream-double-close.js +++ b/test/parallel/test-fs-stream-double-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-symlink-dir-junction-relative.js b/test/parallel/test-fs-symlink-dir-junction-relative.js index 5e4ce38b916393..6bf9e3f5b2d14b 100644 --- a/test/parallel/test-fs-symlink-dir-junction-relative.js +++ b/test/parallel/test-fs-symlink-dir-junction-relative.js @@ -1,3 +1,4 @@ +'use strict'; // Test creating and resolving relative junction or symbolic link var common = require('../common'); diff --git a/test/parallel/test-fs-symlink-dir-junction.js b/test/parallel/test-fs-symlink-dir-junction.js index 27d3e5103d9124..84d6c066213f28 100644 --- a/test/parallel/test-fs-symlink-dir-junction.js +++ b/test/parallel/test-fs-symlink-dir-junction.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-symlink.js b/test/parallel/test-fs-symlink.js index 533f22672da001..e7faef930e4817 100644 --- a/test/parallel/test-fs-symlink.js +++ b/test/parallel/test-fs-symlink.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-sync-fd-leak.js b/test/parallel/test-fs-sync-fd-leak.js index ab851b1a16f333..5f2b63125a1d0f 100644 --- a/test/parallel/test-fs-sync-fd-leak.js +++ b/test/parallel/test-fs-sync-fd-leak.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-truncate-GH-6233.js b/test/parallel/test-fs-truncate-GH-6233.js index 72dfa136916f87..866315434a0120 100644 --- a/test/parallel/test-fs-truncate-GH-6233.js +++ b/test/parallel/test-fs-truncate-GH-6233.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-truncate-fd.js b/test/parallel/test-fs-truncate-fd.js index 6e9628db867371..ed3aedaee8c805 100644 --- a/test/parallel/test-fs-truncate-fd.js +++ b/test/parallel/test-fs-truncate-fd.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-truncate.js b/test/parallel/test-fs-truncate.js index 7f1dcd0661e3f9..df353f630eb370 100644 --- a/test/parallel/test-fs-truncate.js +++ b/test/parallel/test-fs-truncate.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-utimes.js b/test/parallel/test-fs-utimes.js index e877b3dfdc56d5..863d66d89e424b 100644 --- a/test/parallel/test-fs-utimes.js +++ b/test/parallel/test-fs-utimes.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); diff --git a/test/parallel/test-fs-write-buffer.js b/test/parallel/test-fs-write-buffer.js index 7dfcc6cd355215..edf33552cb3253 100644 --- a/test/parallel/test-fs-write-buffer.js +++ b/test/parallel/test-fs-write-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'), @@ -9,7 +10,7 @@ var path = require('path'), writeCalled = 0; -fs.open(filename, 'w', 0644, function(err, fd) { +fs.open(filename, 'w', 0o644, function(err, fd) { openCalled++; if (err) throw err; diff --git a/test/parallel/test-fs-write-file-buffer.js b/test/parallel/test-fs-write-file-buffer.js index bdddba9524977e..c1c263d409d173 100644 --- a/test/parallel/test-fs-write-file-buffer.js +++ b/test/parallel/test-fs-write-file-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var join = require('path').join; var util = require('util'); diff --git a/test/parallel/test-fs-write-file-sync.js b/test/parallel/test-fs-write-file-sync.js index 343d179f2a6864..579ccd907c4206 100644 --- a/test/parallel/test-fs-write-file-sync.js +++ b/test/parallel/test-fs-write-file-sync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -15,14 +16,14 @@ fs._closeSync = fs.closeSync; fs.closeSync = closeSync; // Reset the umask for testing -var mask = process.umask(0000); +var mask = process.umask(0o000); // On Windows chmod is only able to manipulate read-only bit. Test if creating // the file in read-only mode works. if (isWindows) { - mode = 0444; + mode = 0o444; } else { - mode = 0755; + mode = 0o755; } // Test writeFileSync @@ -34,7 +35,7 @@ fs.writeFileSync(file1, '123', {mode: mode}); content = fs.readFileSync(file1, {encoding: 'utf8'}); assert.equal('123', content); -assert.equal(mode, fs.statSync(file1).mode & 0777); +assert.equal(mode, fs.statSync(file1).mode & 0o777); removeFile(file1); @@ -58,7 +59,7 @@ assert.equal(0, openCount); function removeFile(file) { try { if (isWindows) - fs.chmodSync(file, 0666); + fs.chmodSync(file, 0o666); fs.unlinkSync(file); } catch (err) { if (err && err.code !== 'ENOENT') diff --git a/test/parallel/test-fs-write-file.js b/test/parallel/test-fs-write-file.js index 4f43197fd6fb9f..b0c52f7a0ef5c7 100644 --- a/test/parallel/test-fs-write-file.js +++ b/test/parallel/test-fs-write-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -55,14 +56,14 @@ fs.writeFile(filename2, buf, function(e) { var filename3 = join(common.tmpDir, 'test3.txt'); common.error('writing to ' + filename3); -var m = 0600; +var m = 0o600; fs.writeFile(filename3, n, { mode: m }, function(e) { if (e) throw e; // windows permissions aren't unix if (process.platform !== 'win32') { var st = fs.statSync(filename3); - assert.equal(st.mode & 0700, m); + assert.equal(st.mode & 0o700, m); } ncallbacks++; diff --git a/test/parallel/test-fs-write-no-fd.js b/test/parallel/test-fs-write-no-fd.js index 143928e7836ea7..5b38ce6ba814c4 100644 --- a/test/parallel/test-fs-write-no-fd.js +++ b/test/parallel/test-fs-write-no-fd.js @@ -1,3 +1,4 @@ +'use strict'; const common = require('../common'); const fs = require('fs'); const assert = require('assert'); diff --git a/test/parallel/test-fs-write-stream-change-open.js b/test/parallel/test-fs-write-stream-change-open.js index ca02e3959cbbd0..43b57f5c72519e 100644 --- a/test/parallel/test-fs-write-stream-change-open.js +++ b/test/parallel/test-fs-write-stream-change-open.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -21,7 +22,7 @@ fs.close = function(fd) { assert.ok(fd, 'fs.close must not be called with an undefined fd.'); fs.close = _fs_close; fs.open = _fs_open; -} +}; stream.write('foo'); stream.end(); diff --git a/test/parallel/test-fs-write-stream-end.js b/test/parallel/test-fs-write-stream-end.js index 886df63660d15c..1a4c0a89d693a7 100644 --- a/test/parallel/test-fs-write-stream-end.js +++ b/test/parallel/test-fs-write-stream-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-write-stream-err.js b/test/parallel/test-fs-write-stream-err.js index 61d6df5d5fb57e..f3a608b62dc577 100644 --- a/test/parallel/test-fs-write-stream-err.js +++ b/test/parallel/test-fs-write-stream-err.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-write-stream.js b/test/parallel/test-fs-write-stream.js index ef7822af48a365..bf78b1ee521469 100644 --- a/test/parallel/test-fs-write-stream.js +++ b/test/parallel/test-fs-write-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -13,7 +14,7 @@ var file = path.join(common.tmpDir, 'write.txt'); fs.close = function(fd) { assert.ok(fd, 'fs.close must not be called without an undefined fd.'); fs.close = _fs_close; - } + }; stream.destroy(); })(); diff --git a/test/parallel/test-fs-write-string-coerce.js b/test/parallel/test-fs-write-string-coerce.js index 1320acca2c1b4c..32f73172b76e5f 100644 --- a/test/parallel/test-fs-write-string-coerce.js +++ b/test/parallel/test-fs-write-string-coerce.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -8,7 +9,7 @@ var data = true; var expected = data + ''; var found; -fs.open(fn, 'w', 0644, function(err, fd) { +fs.open(fn, 'w', 0o644, function(err, fd) { if (err) throw err; console.log('open done'); fs.write(fd, data, 0, 'utf8', function(err, written) { diff --git a/test/parallel/test-fs-write-sync.js b/test/parallel/test-fs-write-sync.js index 59e2f90f92d6dc..2cdce58d874978 100644 --- a/test/parallel/test-fs-write-sync.js +++ b/test/parallel/test-fs-write-sync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-write.js b/test/parallel/test-fs-write.js index 49b4ec53169137..a3d4cf83f8c85e 100644 --- a/test/parallel/test-fs-write.js +++ b/test/parallel/test-fs-write.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -9,7 +10,7 @@ var expected = 'ümlaut.'; var constants = require('constants'); var found, found2; -fs.open(fn, 'w', 0644, function(err, fd) { +fs.open(fn, 'w', 0o644, function(err, fd) { if (err) throw err; console.log('open done'); fs.write(fd, '', 0, 'utf8', function(err, written) { @@ -28,7 +29,7 @@ fs.open(fn, 'w', 0644, function(err, fd) { }); -fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0644, +fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0o644, function(err, fd) { if (err) throw err; console.log('open done'); diff --git a/test/parallel/test-global.js b/test/parallel/test-global.js index a1ddc72f6290eb..82d8ee054c5860 100644 --- a/test/parallel/test-global.js +++ b/test/parallel/test-global.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-handle-wrap-close-abort.js b/test/parallel/test-handle-wrap-close-abort.js index c1179f72a13946..8e2388fa84d809 100644 --- a/test/parallel/test-handle-wrap-close-abort.js +++ b/test/parallel/test-handle-wrap-close-abort.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); process.on('uncaughtException', function() { }); diff --git a/test/parallel/test-http-1.0-keep-alive.js b/test/parallel/test-http-1.0-keep-alive.js index b67b48969c81e2..eac0fe51e2206a 100644 --- a/test/parallel/test-http-1.0-keep-alive.js +++ b/test/parallel/test-http-1.0-keep-alive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -96,7 +97,7 @@ function check(tests) { var ctx = test.responses[current]; console.error('< SERVER SENDING RESPONSE', ctx); res.writeHead(200, ctx.headers); - ctx.chunks.slice(0, -1).forEach(function(chunk) { res.write(chunk) }); + ctx.chunks.slice(0, -1).forEach(function(chunk) { res.write(chunk); }); res.end(ctx.chunks[ctx.chunks.length - 1]); } diff --git a/test/parallel/test-http-1.0.js b/test/parallel/test-http-1.0.js index f1408d2f53412a..bf55c616d91996 100644 --- a/test/parallel/test-http-1.0.js +++ b/test/parallel/test-http-1.0.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-304.js b/test/parallel/test-http-304.js index a2cc95e57db60d..e206f5bb70a3e1 100644 --- a/test/parallel/test-http-304.js +++ b/test/parallel/test-http-304.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-abort-before-end.js b/test/parallel/test-http-abort-before-end.js index 351ec86c2b8b95..c0cee3886f4406 100644 --- a/test/parallel/test-http-abort-before-end.js +++ b/test/parallel/test-http-abort-before-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'); var assert = require('assert'); diff --git a/test/parallel/test-http-abort-client.js b/test/parallel/test-http-abort-client.js index 40cf64c2cb0559..e24ded11d1a7ec 100644 --- a/test/parallel/test-http-abort-client.js +++ b/test/parallel/test-http-abort-client.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'); var assert = require('assert'); @@ -38,7 +39,7 @@ server.listen(common.PORT, function() { res.socket.on('close', function() { console.log('socket closed, but not res'); - }) + }); // it would be nice if this worked: res.on('close', function() { diff --git a/test/parallel/test-http-abort-queued.js b/test/parallel/test-http-abort-queued.js index 1ef24acd509c1a..f2b0120366c374 100644 --- a/test/parallel/test-http-abort-queued.js +++ b/test/parallel/test-http-abort-queued.js @@ -1,10 +1,11 @@ +'use strict'; var assert = require('assert'), common = require('../common'), http = require('http'); var complete; -var server = http.createServer(function (req, res) { +var server = http.createServer(function(req, res) { // We should not see the queued /thatotherone request within the server // as it should be aborted before it is sent. assert.equal(req.url, '/'); @@ -12,13 +13,13 @@ var server = http.createServer(function (req, res) { res.writeHead(200); res.write('foo'); - complete = complete || function () { + complete = complete || function() { res.end(); }; }); -server.listen(common.PORT, function () { +server.listen(common.PORT, function() { console.log('listen', server.address().port); var agent = new http.Agent({maxSockets: 1}); diff --git a/test/parallel/test-http-after-connect.js b/test/parallel/test-http-after-connect.js index bff9170a217b81..19011fcbcb4fc4 100644 --- a/test/parallel/test-http-after-connect.js +++ b/test/parallel/test-http-after-connect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-agent-destroyed-socket.js b/test/parallel/test-http-agent-destroyed-socket.js index a2fe54d1dc6848..954acc998c035d 100644 --- a/test/parallel/test-http-agent-destroyed-socket.js +++ b/test/parallel/test-http-agent-destroyed-socket.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-agent-false.js b/test/parallel/test-http-agent-false.js index 95c375ac37c7d3..ad8de89f2038e9 100644 --- a/test/parallel/test-http-agent-false.js +++ b/test/parallel/test-http-agent-false.js @@ -1,10 +1,11 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); -// sending `agent: false` when `port: null` is also passed in (i.e. the result of -// a `url.parse()` call with the default port used, 80 or 443), should not result -// in an assertion error... +// sending `agent: false` when `port: null` is also passed in (i.e. the result +// of a `url.parse()` call with the default port used, 80 or 443), should not +// result in an assertion error... var opts = { host: '127.0.0.1', port: null, @@ -19,8 +20,8 @@ process.on('exit', function() { }); // we just want an "error" (no local HTTP server on port 80) or "response" -// to happen (user happens ot have HTTP server running on port 80). As long as the -// process doesn't crash from a C++ assertion then we're good. +// to happen (user happens ot have HTTP server running on port 80). +// As long as the process doesn't crash from a C++ assertion then we're good. var req = http.request(opts); req.on('response', function(res) { good = true; diff --git a/test/parallel/test-http-agent-keepalive.js b/test/parallel/test-http-agent-keepalive.js index 7dfd6f789ed921..f82af380bce1a9 100644 --- a/test/parallel/test-http-agent-keepalive.js +++ b/test/parallel/test-http-agent-keepalive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -11,14 +12,14 @@ var agent = new Agent({ maxFreeSockets: 5 }); -var server = http.createServer(function (req, res) { +var server = http.createServer(function(req, res) { if (req.url === '/error') { res.destroy(); return; } else if (req.url === '/remote_close') { // cache the socket, close it after 100ms var socket = res.connection; - setTimeout(function () { + setTimeout(function() { socket.end(); }, 100); } @@ -44,13 +45,13 @@ function checkDataAndSockets(body) { function second() { // request second, use the same socket - get('/second', function (res) { + get('/second', function(res) { assert.equal(res.statusCode, 200); res.on('data', checkDataAndSockets); - res.on('end', function () { + res.on('end', function() { assert.equal(agent.sockets[name].length, 1); assert.equal(agent.freeSockets[name], undefined); - process.nextTick(function () { + process.nextTick(function() { assert.equal(agent.sockets[name], undefined); assert.equal(agent.freeSockets[name].length, 1); remoteClose(); @@ -61,17 +62,17 @@ function second() { function remoteClose() { // mock remote server close the socket - get('/remote_close', function (res) { + get('/remote_close', function(res) { assert.deepEqual(res.statusCode, 200); res.on('data', checkDataAndSockets); - res.on('end', function () { + res.on('end', function() { assert.equal(agent.sockets[name].length, 1); assert.equal(agent.freeSockets[name], undefined); - process.nextTick(function () { + process.nextTick(function() { assert.equal(agent.sockets[name], undefined); assert.equal(agent.freeSockets[name].length, 1); // waitting remote server close the socket - setTimeout(function () { + setTimeout(function() { assert.equal(agent.sockets[name], undefined); assert.equal(agent.freeSockets[name], undefined, 'freeSockets is not empty'); @@ -84,16 +85,16 @@ function remoteClose() { function remoteError() { // remove server will destroy ths socket - var req = get('/error', function (res) { + var req = get('/error', function(res) { throw new Error('should not call this function'); }); - req.on('error', function (err) { + req.on('error', function(err) { assert.ok(err); assert.equal(err.message, 'socket hang up'); assert.equal(agent.sockets[name].length, 1); assert.equal(agent.freeSockets[name], undefined); // Wait socket 'close' event emit - setTimeout(function () { + setTimeout(function() { assert.equal(agent.sockets[name], undefined); assert.equal(agent.freeSockets[name], undefined); done(); @@ -108,13 +109,13 @@ function done() { server.listen(common.PORT, function() { // request first, and keep alive - get('/first', function (res) { + get('/first', function(res) { assert.equal(res.statusCode, 200); res.on('data', checkDataAndSockets); - res.on('end', function () { + res.on('end', function() { assert.equal(agent.sockets[name].length, 1); assert.equal(agent.freeSockets[name], undefined); - process.nextTick(function () { + process.nextTick(function() { assert.equal(agent.sockets[name], undefined); assert.equal(agent.freeSockets[name].length, 1); second(); diff --git a/test/parallel/test-http-agent-maxsockets.js b/test/parallel/test-http-agent-maxsockets.js index 0f349eac549abf..e11aa2addad746 100644 --- a/test/parallel/test-http-agent-maxsockets.js +++ b/test/parallel/test-http-agent-maxsockets.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-agent-no-protocol.js b/test/parallel/test-http-agent-no-protocol.js index 1f910c33e53932..d5b7e5e19440f9 100644 --- a/test/parallel/test-http-agent-no-protocol.js +++ b/test/parallel/test-http-agent-no-protocol.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -21,7 +22,7 @@ var server = http.createServer(function(req, res) { opts.agent = new http.Agent(); opts.agent.protocol = null; - http.get(opts, function (res) { + http.get(opts, function(res) { response++; res.resume(); server.close(); diff --git a/test/parallel/test-http-agent-null.js b/test/parallel/test-http-agent-null.js index 397a5e0f4bbd72..e118738f664083 100644 --- a/test/parallel/test-http-agent-null.js +++ b/test/parallel/test-http-agent-null.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-agent.js b/test/parallel/test-http-agent.js index a485bc996ae2d8..09ba9c34e2936d 100644 --- a/test/parallel/test-http-agent.js +++ b/test/parallel/test-http-agent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-allow-req-after-204-res.js b/test/parallel/test-http-allow-req-after-204-res.js index e671bec029e159..ba98138bdca568 100644 --- a/test/parallel/test-http-allow-req-after-204-res.js +++ b/test/parallel/test-http-allow-req-after-204-res.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'); var assert = require('assert'); diff --git a/test/parallel/test-http-automatic-headers.js b/test/parallel/test-http-automatic-headers.js index 76e5a61318c75d..8c454517020460 100644 --- a/test/parallel/test-http-automatic-headers.js +++ b/test/parallel/test-http-automatic-headers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-bind-twice.js b/test/parallel/test-http-bind-twice.js index 187f35ab879e4f..4dde7c6d252c6a 100644 --- a/test/parallel/test-http-bind-twice.js +++ b/test/parallel/test-http-bind-twice.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-blank-header.js b/test/parallel/test-http-blank-header.js index 1fb1e0af96bec7..00a94d0b839f42 100644 --- a/test/parallel/test-http-blank-header.js +++ b/test/parallel/test-http-blank-header.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-buffer-sanity.js b/test/parallel/test-http-buffer-sanity.js index f55d36c770f277..4b120311d7dac9 100644 --- a/test/parallel/test-http-buffer-sanity.js +++ b/test/parallel/test-http-buffer-sanity.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-byteswritten.js b/test/parallel/test-http-byteswritten.js index 00ba09143ec9c8..974f446dd436b4 100644 --- a/test/parallel/test-http-byteswritten.js +++ b/test/parallel/test-http-byteswritten.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-http-chunked-304.js b/test/parallel/test-http-chunked-304.js index 86e0b0d11d1dfd..0f979420488d60 100644 --- a/test/parallel/test-http-chunked-304.js +++ b/test/parallel/test-http-chunked-304.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-chunked.js b/test/parallel/test-http-chunked.js index b666e051cc07b1..74b6943ab41f41 100644 --- a/test/parallel/test-http-chunked.js +++ b/test/parallel/test-http-chunked.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -24,7 +25,7 @@ server.listen(common.PORT, function() { port: common.PORT }, function(x) { x.setEncoding('utf8'); - x.on('data', function(c) {data += c}); + x.on('data', function(c) {data += c;}); x.on('error', function(e) { throw e; }); @@ -36,7 +37,7 @@ server.listen(common.PORT, function() { server.close(); }); }); - get.on('error', function(e) {throw e}); + get.on('error', function(e) {throw e;}); get.end(); }); diff --git a/test/parallel/test-http-client-abort-event.js b/test/parallel/test-http-client-abort-event.js index 1549d06101a647..b428038028ad8e 100644 --- a/test/parallel/test-http-client-abort-event.js +++ b/test/parallel/test-http-client-abort-event.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var http = require('http'); var common = require('../common'); @@ -25,4 +26,4 @@ server.listen(common.PORT, function() { process.on('exit', function() { assert.equal(count, 1); -}) +}); diff --git a/test/parallel/test-http-client-abort.js b/test/parallel/test-http-client-abort.js index 1359df5a6c4b3d..c3353bb72201b6 100644 --- a/test/parallel/test-http-client-abort.js +++ b/test/parallel/test-http-client-abort.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-abort2.js b/test/parallel/test-http-client-abort2.js index c7c19acccf3ea5..3f7ae98fa25820 100644 --- a/test/parallel/test-http-client-abort2.js +++ b/test/parallel/test-http-client-abort2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-agent.js b/test/parallel/test-http-client-agent.js index e97a14720f4a0f..afe98902e5b6fc 100644 --- a/test/parallel/test-http-client-agent.js +++ b/test/parallel/test-http-client-agent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-default-headers-exist.js b/test/parallel/test-http-client-default-headers-exist.js index 02175384970de1..94106285beca97 100644 --- a/test/parallel/test-http-client-default-headers-exist.js +++ b/test/parallel/test-http-client-default-headers-exist.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-encoding.js b/test/parallel/test-http-client-encoding.js index a93b33620fe934..dd696f4dff608a 100644 --- a/test/parallel/test-http-client-encoding.js +++ b/test/parallel/test-http-client-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-client-get-url.js b/test/parallel/test-http-client-get-url.js index 03fa3331e95160..1dd23143e46c68 100644 --- a/test/parallel/test-http-client-get-url.js +++ b/test/parallel/test-http-client-get-url.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-parse-error.js b/test/parallel/test-http-client-parse-error.js index 38f2628741dd93..43f85853b3bbeb 100644 --- a/test/parallel/test-http-client-parse-error.js +++ b/test/parallel/test-http-client-parse-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-client-pipe-end.js b/test/parallel/test-http-client-pipe-end.js index 6f05d3093123b5..d794aae446c4fa 100644 --- a/test/parallel/test-http-client-pipe-end.js +++ b/test/parallel/test-http-client-pipe-end.js @@ -1,3 +1,4 @@ +'use strict'; // see https://github.com/joyent/node/issues/3257 var common = require('../common'); @@ -23,7 +24,7 @@ server.listen(common.PIPE, function() { req.write('.'); - sched(function() { req.end() }, 5); + sched(function() { req.end(); }, 5); }); // schedule a callback after `ticks` event loop ticks diff --git a/test/parallel/test-http-client-race-2.js b/test/parallel/test-http-client-race-2.js index fabb2c50a86984..0a98e06c7bf062 100644 --- a/test/parallel/test-http-client-race-2.js +++ b/test/parallel/test-http-client-race-2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -79,7 +80,7 @@ server.on('listening', function() { req3.end(); req3.on('response', function(res3) { res3.setEncoding('utf8'); - res3.on('data', function(chunk) { body3 += chunk }); + res3.on('data', function(chunk) { body3 += chunk; }); res3.on('end', function() { server.close(); }); }); }); diff --git a/test/parallel/test-http-client-race.js b/test/parallel/test-http-client-race.js index c284fbae773e68..11dcb7ae4ca89e 100644 --- a/test/parallel/test-http-client-race.js +++ b/test/parallel/test-http-client-race.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-read-in-error.js b/test/parallel/test-http-client-read-in-error.js index 6568d7e28d0223..8d74aecb51b91c 100644 --- a/test/parallel/test-http-client-read-in-error.js +++ b/test/parallel/test-http-client-read-in-error.js @@ -1,3 +1,4 @@ +'use strict'; var net = require('net'); var http = require('http'); var util = require('util'); diff --git a/test/parallel/test-http-client-readable.js b/test/parallel/test-http-client-readable.js index e690ba7ba5afc8..ba9fdd658c3864 100644 --- a/test/parallel/test-http-client-readable.js +++ b/test/parallel/test-http-client-readable.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-response-domain.js b/test/parallel/test-http-client-response-domain.js index 1c38a1a254eaf4..1637882a3c251d 100644 --- a/test/parallel/test-http-client-response-domain.js +++ b/test/parallel/test-http-client-response-domain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), http = require('http'), diff --git a/test/parallel/test-http-client-timeout-agent.js b/test/parallel/test-http-client-timeout-agent.js index a928b12090e704..809742f5628df5 100644 --- a/test/parallel/test-http-client-timeout-agent.js +++ b/test/parallel/test-http-client-timeout-agent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -23,35 +24,35 @@ var server = http.createServer(function(req, res) { res.write(reqid.toString()); res.end(); } - request_number+=1; + request_number += 1; }); server.listen(options.port, options.host, function() { var req; - for (requests_sent = 0; requests_sent < 30; requests_sent+=1) { + for (requests_sent = 0; requests_sent < 30; requests_sent += 1) { options.path = '/' + requests_sent; req = http.request(options); req.id = requests_sent; req.on('response', function(res) { res.on('data', function(data) { - console.log('res#'+this.req.id+' data:'+data); + console.log('res#' + this.req.id + ' data:' + data); }); res.on('end', function(data) { - console.log('res#'+this.req.id+' end'); + console.log('res#' + this.req.id + ' end'); requests_done += 1; }); }); req.on('close', function() { - console.log('req#'+this.id+' close'); + console.log('req#' + this.id + ' close'); }); req.on('error', function() { - console.log('req#'+this.id+' error'); + console.log('req#' + this.id + ' error'); this.destroy(); }); - req.setTimeout(50, function () { + req.setTimeout(50, function() { var req = this; - console.log('req#'+this.id + ' timeout'); + console.log('req#' + this.id + ' timeout'); req.abort(); requests_done += 1; }); @@ -71,5 +72,6 @@ server.listen(options.port, options.host, function() { process.on('exit', function() { console.error('done=%j sent=%j', requests_done, requests_sent); - assert.ok(requests_done == requests_sent, 'timeout on http request called too much'); + assert.ok(requests_done == requests_sent, + 'timeout on http request called too much'); }); diff --git a/test/parallel/test-http-client-timeout-event.js b/test/parallel/test-http-client-timeout-event.js index c975d69d399745..c9d65941923408 100644 --- a/test/parallel/test-http-client-timeout-event.js +++ b/test/parallel/test-http-client-timeout-event.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -26,14 +27,14 @@ server.listen(options.port, options.host, function() { var timeout_events = 0; req.setTimeout(1); - req.on('timeout', function () { + req.on('timeout', function() { timeout_events += 1; }); - setTimeout(function () { + setTimeout(function() { req.destroy(); assert.equal(timeout_events, 1); }, 100); - setTimeout(function () { + setTimeout(function() { req.end(); }, 50); }); diff --git a/test/parallel/test-http-client-timeout-with-data.js b/test/parallel/test-http-client-timeout-with-data.js index accf8c1341b86c..0aefe62ef45055 100644 --- a/test/parallel/test-http-client-timeout-with-data.js +++ b/test/parallel/test-http-client-timeout-with-data.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -20,7 +21,7 @@ var options = { var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Length':'2'}); res.write('*'); - setTimeout(function() { res.end('*') }, 100); + setTimeout(function() { res.end('*'); }, 100); }); server.listen(options.port, options.host, function() { diff --git a/test/parallel/test-http-client-timeout.js b/test/parallel/test-http-client-timeout.js index 8ea36de41ec4c1..63ef5c067a5bd3 100644 --- a/test/parallel/test-http-client-timeout.js +++ b/test/parallel/test-http-client-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-unescaped-path.js b/test/parallel/test-http-client-unescaped-path.js index 51e1fc7828be86..1536916ae9b49c 100644 --- a/test/parallel/test-http-client-unescaped-path.js +++ b/test/parallel/test-http-client-unescaped-path.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-upload-buf.js b/test/parallel/test-http-client-upload-buf.js index 5e544ccf518123..760f9c9562a678 100644 --- a/test/parallel/test-http-client-upload-buf.js +++ b/test/parallel/test-http-client-upload-buf.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-upload.js b/test/parallel/test-http-client-upload.js index 44fd5eabf23ab4..48ebfcc74de5ac 100644 --- a/test/parallel/test-http-client-upload.js +++ b/test/parallel/test-http-client-upload.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-conn-reset.js b/test/parallel/test-http-conn-reset.js index d340aa744c494a..2f047a2de4009a 100644 --- a/test/parallel/test-http-conn-reset.js +++ b/test/parallel/test-http-conn-reset.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-connect.js b/test/parallel/test-http-connect.js index 5ba24df5c18a9a..92fed5a72556db 100644 --- a/test/parallel/test-http-connect.js +++ b/test/parallel/test-http-connect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-content-length.js b/test/parallel/test-http-content-length.js index 07180f26ad84ed..6c9576cdabf563 100644 --- a/test/parallel/test-http-content-length.js +++ b/test/parallel/test-http-content-length.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-contentLength0.js b/test/parallel/test-http-contentLength0.js index 9b565c5470a246..9004649d1d2057 100644 --- a/test/parallel/test-http-contentLength0.js +++ b/test/parallel/test-http-contentLength0.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'); diff --git a/test/parallel/test-http-createConnection.js b/test/parallel/test-http-createConnection.js index 1da2d18f414bf8..48a7d7dbe68ea3 100644 --- a/test/parallel/test-http-createConnection.js +++ b/test/parallel/test-http-createConnection.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -14,7 +15,7 @@ var server = http.createServer(function(req, res) { res.end(); response++; }).listen(common.PORT, '127.0.0.1', function() { - http.get({ createConnection: createConnection }, function (res) { + http.get({ createConnection: createConnection }, function(res) { res.resume(); server.close(); }); diff --git a/test/parallel/test-http-curl-chunk-problem.js b/test/parallel/test-http-curl-chunk-problem.js index fcb186153dc933..55fce4ad5e60e4 100644 --- a/test/parallel/test-http-curl-chunk-problem.js +++ b/test/parallel/test-http-curl-chunk-problem.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); if (!common.opensslCli) { diff --git a/test/parallel/test-http-date-header.js b/test/parallel/test-http-date-header.js index 293a9b99291255..4c73800a8e908c 100644 --- a/test/parallel/test-http-date-header.js +++ b/test/parallel/test-http-date-header.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-default-encoding.js b/test/parallel/test-http-default-encoding.js index 6a2ac36ebd4b90..a40c8841eceab9 100644 --- a/test/parallel/test-http-default-encoding.js +++ b/test/parallel/test-http-default-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-default-port.js b/test/parallel/test-http-default-port.js index 5f702073121128..457424ecfa9397 100644 --- a/test/parallel/test-http-default-port.js +++ b/test/parallel/test-http-default-port.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'), PORT = common.PORT, diff --git a/test/parallel/test-http-destroyed-socket-write2.js b/test/parallel/test-http-destroyed-socket-write2.js index e7a47ca9cfe95f..5bbb3bbc946f7d 100644 --- a/test/parallel/test-http-destroyed-socket-write2.js +++ b/test/parallel/test-http-destroyed-socket-write2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-dns-error.js b/test/parallel/test-http-dns-error.js index 15547cd39450d1..55195e45b715ff 100644 --- a/test/parallel/test-http-dns-error.js +++ b/test/parallel/test-http-dns-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-end-throw-socket-handling.js b/test/parallel/test-http-end-throw-socket-handling.js index 92a5ae6a38d0fb..204c0f73335480 100644 --- a/test/parallel/test-http-end-throw-socket-handling.js +++ b/test/parallel/test-http-end-throw-socket-handling.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -19,8 +20,8 @@ server.listen(common.PORT, function() { for (var i = 0; i < 10; i++) { var options = { port: common.PORT }; - var req = http.request(options, function (res) { - res.resume() + var req = http.request(options, function(res) { + res.resume(); res.on('end', function() { throw new Error('gleep glorp'); }); diff --git a/test/parallel/test-http-eof-on-connect.js b/test/parallel/test-http-eof-on-connect.js index a08ac9c7b0e6c9..e676643bab4911 100644 --- a/test/parallel/test-http-eof-on-connect.js +++ b/test/parallel/test-http-eof-on-connect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-exceptions.js b/test/parallel/test-http-exceptions.js index 6e0b5b9a6b8166..dc2d5583ddbaf9 100644 --- a/test/parallel/test-http-exceptions.js +++ b/test/parallel/test-http-exceptions.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-exit-delay.js b/test/parallel/test-http-exit-delay.js index 191b96d28b1e74..b06b33b5948eaf 100644 --- a/test/parallel/test-http-exit-delay.js +++ b/test/parallel/test-http-exit-delay.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var http = require('http'); diff --git a/test/parallel/test-http-expect-continue.js b/test/parallel/test-http-expect-continue.js index ed6de310955383..aef4a98d84c9e2 100644 --- a/test/parallel/test-http-expect-continue.js +++ b/test/parallel/test-http-expect-continue.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-extra-response.js b/test/parallel/test-http-extra-response.js index ac2d9b6157c967..bfd9b59462c685 100644 --- a/test/parallel/test-http-extra-response.js +++ b/test/parallel/test-http-extra-response.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-flush-headers.js b/test/parallel/test-http-flush-headers.js index ede0fa52021233..da1bd24c54a884 100644 --- a/test/parallel/test-http-flush-headers.js +++ b/test/parallel/test-http-flush-headers.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); const server = http.createServer(); -server.on('request', function(req, res){ +server.on('request', function(req, res) { assert(req.headers['foo'], 'bar'); res.end('ok'); server.close(); diff --git a/test/parallel/test-http-flush.js b/test/parallel/test-http-flush.js index 8d5a593cd9d21d..cac1caf752bee6 100644 --- a/test/parallel/test-http-flush.js +++ b/test/parallel/test-http-flush.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-full-response.js b/test/parallel/test-http-full-response.js index 4f3ce63dd85bed..da1b6d7f223496 100644 --- a/test/parallel/test-http-full-response.js +++ b/test/parallel/test-http-full-response.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); // This test requires the program 'ab' diff --git a/test/parallel/test-http-get-pipeline-problem.js b/test/parallel/test-http-get-pipeline-problem.js index 4d36cd3f7ea6f2..9c51bd11912257 100644 --- a/test/parallel/test-http-get-pipeline-problem.js +++ b/test/parallel/test-http-get-pipeline-problem.js @@ -1,3 +1,4 @@ +'use strict'; // We are demonstrating a problem with http.get when queueing up many // transfers. The server simply introduces some delay and sends a file. // Note this is demonstrated with connection: close. diff --git a/test/parallel/test-http-head-request.js b/test/parallel/test-http-head-request.js index 2310a6f83162f3..5a6f90507cf303 100644 --- a/test/parallel/test-http-head-request.js +++ b/test/parallel/test-http-head-request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-head-response-has-no-body-end.js b/test/parallel/test-http-head-response-has-no-body-end.js index 4f0fb5341ef10e..e0fdb131ed3378 100644 --- a/test/parallel/test-http-head-response-has-no-body-end.js +++ b/test/parallel/test-http-head-response-has-no-body-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-head-response-has-no-body.js b/test/parallel/test-http-head-response-has-no-body.js index 73fcf0b31f368d..ef1fc530db19c9 100644 --- a/test/parallel/test-http-head-response-has-no-body.js +++ b/test/parallel/test-http-head-response-has-no-body.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-header-read.js b/test/parallel/test-http-header-read.js index 0cba3d37415617..6266f8b11ffd2c 100644 --- a/test/parallel/test-http-header-read.js +++ b/test/parallel/test-http-header-read.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-header-response-splitting.js b/test/parallel/test-http-header-response-splitting.js index 148de1d245b040..b499ae33d157cc 100644 --- a/test/parallel/test-http-header-response-splitting.js +++ b/test/parallel/test-http-header-response-splitting.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), http = require('http'); diff --git a/test/parallel/test-http-hex-write.js b/test/parallel/test-http-hex-write.js index acce151b20af79..371bbe7a43cb75 100644 --- a/test/parallel/test-http-hex-write.js +++ b/test/parallel/test-http-hex-write.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-host-headers.js b/test/parallel/test-http-host-headers.js index 10e50306609d67..b5c083dfdf6d15 100644 --- a/test/parallel/test-http-host-headers.js +++ b/test/parallel/test-http-host-headers.js @@ -1,3 +1,4 @@ +'use strict'; var http = require('http'), common = require('../common'), assert = require('assert'), diff --git a/test/parallel/test-http-incoming-pipelined-socket-destroy.js b/test/parallel/test-http-incoming-pipelined-socket-destroy.js index 26b704e6d5b5ba..21cd3e69dfd746 100644 --- a/test/parallel/test-http-incoming-pipelined-socket-destroy.js +++ b/test/parallel/test-http-incoming-pipelined-socket-destroy.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -42,7 +43,7 @@ function generator(seeds) { return 'GET /' + r + ' HTTP/1.1\r\n' + 'Host: localhost:' + common.PORT + '\r\n' + '\r\n' + - '\r\n' + '\r\n'; }).join(''); } diff --git a/test/parallel/test-http-keep-alive-close-on-header.js b/test/parallel/test-http-keep-alive-close-on-header.js index 200f017a802d57..9ed6077b943aa8 100644 --- a/test/parallel/test-http-keep-alive-close-on-header.js +++ b/test/parallel/test-http-keep-alive-close-on-header.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-keep-alive.js b/test/parallel/test-http-keep-alive.js index 58c7061059a90c..f89f7698c46ebd 100644 --- a/test/parallel/test-http-keep-alive.js +++ b/test/parallel/test-http-keep-alive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-keepalive-client.js b/test/parallel/test-http-keepalive-client.js index 6bc459e3b96fd0..c573ac82d6f884 100644 --- a/test/parallel/test-http-keepalive-client.js +++ b/test/parallel/test-http-keepalive-client.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -66,6 +67,6 @@ function makeRequest(n) { } process.on('exit', function() { - assert.equal(actualRequests, expectRequests) + assert.equal(actualRequests, expectRequests); console.log('ok'); }); diff --git a/test/parallel/test-http-keepalive-maxsockets.js b/test/parallel/test-http-keepalive-maxsockets.js index e0e27f5e240cfe..a5382b6e328485 100644 --- a/test/parallel/test-http-keepalive-maxsockets.js +++ b/test/parallel/test-http-keepalive-maxsockets.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-keepalive-request.js b/test/parallel/test-http-keepalive-request.js index 51e9d66b1f739c..8736c9cd4f88ce 100644 --- a/test/parallel/test-http-keepalive-request.js +++ b/test/parallel/test-http-keepalive-request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -66,6 +67,6 @@ function makeRequest(n) { } process.on('exit', function() { - assert.equal(actualRequests, expectRequests) + assert.equal(actualRequests, expectRequests); console.log('ok'); }); diff --git a/test/parallel/test-http-legacy.js b/test/parallel/test-http-legacy.js index 7a3ae3572519f6..039037114d37d4 100644 --- a/test/parallel/test-http-legacy.js +++ b/test/parallel/test-http-legacy.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-localaddress-bind-error.js b/test/parallel/test-http-localaddress-bind-error.js index 9ee8c1d74f950e..80c7cab7c8e1ad 100644 --- a/test/parallel/test-http-localaddress-bind-error.js +++ b/test/parallel/test-http-localaddress-bind-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -6,7 +7,7 @@ var invalidLocalAddress = '1.2.3.4'; var gotError = false; var server = http.createServer(function(req, res) { - console.log("Connect from: " + req.connection.remoteAddress); + console.log('Connect from: ' + req.connection.remoteAddress); req.on('end', function() { res.writeHead(200, { 'Content-Type': 'text/plain' }); @@ -15,7 +16,7 @@ var server = http.createServer(function(req, res) { req.resume(); }); -server.listen(common.PORT, "127.0.0.1", function() { +server.listen(common.PORT, '127.0.0.1', function() { var req = http.request({ host: 'localhost', port: common.PORT, diff --git a/test/parallel/test-http-localaddress.js b/test/parallel/test-http-localaddress.js index 3cd821315253c9..9cc6a80d0b4974 100644 --- a/test/parallel/test-http-localaddress.js +++ b/test/parallel/test-http-localaddress.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'), assert = require('assert'); @@ -7,8 +8,8 @@ if (!common.hasMultiLocalhost()) { process.exit(); } -var server = http.createServer(function (req, res) { - console.log("Connect from: " + req.connection.remoteAddress); +var server = http.createServer(function(req, res) { + console.log('Connect from: ' + req.connection.remoteAddress); assert.equal('127.0.0.2', req.connection.remoteAddress); req.on('end', function() { @@ -18,7 +19,7 @@ var server = http.createServer(function (req, res) { req.resume(); }); -server.listen(common.PORT, "127.0.0.1", function() { +server.listen(common.PORT, '127.0.0.1', function() { var options = { host: 'localhost', port: common.PORT, path: '/', diff --git a/test/parallel/test-http-malformed-request.js b/test/parallel/test-http-malformed-request.js index 26a0f340794cfc..5f65113afd4fc0 100644 --- a/test/parallel/test-http-malformed-request.js +++ b/test/parallel/test-http-malformed-request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-many-ended-pipelines.js b/test/parallel/test-http-many-ended-pipelines.js index 6824627151e741..4e0bc7e8ff736f 100644 --- a/test/parallel/test-http-many-ended-pipelines.js +++ b/test/parallel/test-http-many-ended-pipelines.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -28,7 +29,7 @@ server.listen(common.PORT); var client = net.connect({ port: common.PORT, allowHalfOpen: true }); for (var i = 0; i < numRequests; i++) { client.write('GET / HTTP/1.1\r\n' + - 'Host: some.host.name\r\n'+ + 'Host: some.host.name\r\n' + '\r\n\r\n'); } client.end(); diff --git a/test/parallel/test-http-max-headers-count.js b/test/parallel/test-http-max-headers-count.js index ed9b34297b5f39..18b160d0b6d8ed 100644 --- a/test/parallel/test-http-max-headers-count.js +++ b/test/parallel/test-http-max-headers-count.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-methods.js b/test/parallel/test-http-methods.js index 620db49434cdc2..348fd2e519ef64 100644 --- a/test/parallel/test-http-methods.js +++ b/test/parallel/test-http-methods.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-multi-line-headers.js b/test/parallel/test-http-multi-line-headers.js index 44d696a5a0c1d6..0c36b7cbf3cac9 100644 --- a/test/parallel/test-http-multi-line-headers.js +++ b/test/parallel/test-http-multi-line-headers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-mutable-headers.js b/test/parallel/test-http-mutable-headers.js index 296b1622a03394..2a60117328c580 100644 --- a/test/parallel/test-http-mutable-headers.js +++ b/test/parallel/test-http-mutable-headers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -21,10 +22,10 @@ var cookies = [ var s = http.createServer(function(req, res) { switch (test) { case 'headers': - assert.throws(function() { res.setHeader() }); - assert.throws(function() { res.setHeader('someHeader') }); - assert.throws(function() { res.getHeader() }); - assert.throws(function() { res.removeHeader() }); + assert.throws(function() { res.setHeader(); }); + assert.throws(function() { res.setHeader('someHeader'); }); + assert.throws(function() { res.getHeader(); }); + assert.throws(function() { res.removeHeader(); }); res.setHeader('x-test-header', 'testing'); res.setHeader('X-TEST-HEADER2', 'testing'); diff --git a/test/parallel/test-http-no-content-length.js b/test/parallel/test-http-no-content-length.js index 527ffb7d37b4e4..5752e5e924cd1b 100644 --- a/test/parallel/test-http-no-content-length.js +++ b/test/parallel/test-http-no-content-length.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-outgoing-finish.js b/test/parallel/test-http-outgoing-finish.js index e25f8ab743ff1e..2140759139c8ed 100644 --- a/test/parallel/test-http-outgoing-finish.js +++ b/test/parallel/test-http-outgoing-finish.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-parser-bad-ref.js b/test/parallel/test-http-parser-bad-ref.js index 0e2a77bb3a3938..d409dc62d008d9 100644 --- a/test/parallel/test-http-parser-bad-ref.js +++ b/test/parallel/test-http-parser-bad-ref.js @@ -1,3 +1,4 @@ +'use strict'; // Run this program with valgrind or efence with --expose_gc to expose the // problem. diff --git a/test/parallel/test-http-parser-free.js b/test/parallel/test-http-parser-free.js index 52df3836d790c0..af94d0c89c8f52 100644 --- a/test/parallel/test-http-parser-free.js +++ b/test/parallel/test-http-parser-free.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-parser.js b/test/parallel/test-http-parser.js index d8c181bf60f7ce..bb004f864cf468 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-pause-resume-one-end.js b/test/parallel/test-http-pause-resume-one-end.js index cc3e41f3e92c77..2a10aeb3beb9e6 100644 --- a/test/parallel/test-http-pause-resume-one-end.js +++ b/test/parallel/test-http-pause-resume-one-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-pause.js b/test/parallel/test-http-pause.js index cf318d024f0656..70a04657b81011 100644 --- a/test/parallel/test-http-pause.js +++ b/test/parallel/test-http-pause.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-pipe-fs.js b/test/parallel/test-http-pipe-fs.js index 76882d65650bfd..bfee9ce23f1365 100644 --- a/test/parallel/test-http-pipe-fs.js +++ b/test/parallel/test-http-pipe-fs.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-proxy.js b/test/parallel/test-http-proxy.js index 8d27728a92ff34..fc8a753f2485ce 100644 --- a/test/parallel/test-http-proxy.js +++ b/test/parallel/test-http-proxy.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-raw-headers.js b/test/parallel/test-http-raw-headers.js index b4c1401872ae8a..7ecaaa93cfb04e 100644 --- a/test/parallel/test-http-raw-headers.js +++ b/test/parallel/test-http-raw-headers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-remove-header-stays-removed.js b/test/parallel/test-http-remove-header-stays-removed.js index e963989385b336..904b8210103ebf 100644 --- a/test/parallel/test-http-remove-header-stays-removed.js +++ b/test/parallel/test-http-remove-header-stays-removed.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-request-end-twice.js b/test/parallel/test-http-request-end-twice.js index 5518a8140cf463..871880e51463d8 100644 --- a/test/parallel/test-http-request-end-twice.js +++ b/test/parallel/test-http-request-end-twice.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-request-end.js b/test/parallel/test-http-request-end.js index d06c96d8777f5d..43d023028a4fd0 100644 --- a/test/parallel/test-http-request-end.js +++ b/test/parallel/test-http-request-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-request-methods.js b/test/parallel/test-http-request-methods.js index d0b474d712e34d..b29a6663ff6b26 100644 --- a/test/parallel/test-http-request-methods.js +++ b/test/parallel/test-http-request-methods.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-res-write-after-end.js b/test/parallel/test-http-res-write-after-end.js index 295d38aacb0e79..c8b3bf26e0804b 100644 --- a/test/parallel/test-http-res-write-after-end.js +++ b/test/parallel/test-http-res-write-after-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-res-write-end-dont-take-array.js b/test/parallel/test-http-res-write-end-dont-take-array.js index a4dcfcac0f1e41..0befd951f0cf16 100644 --- a/test/parallel/test-http-res-write-end-dont-take-array.js +++ b/test/parallel/test-http-res-write-end-dont-take-array.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-response-close.js b/test/parallel/test-http-response-close.js index 1b3433d79ebe60..82fd782717371c 100644 --- a/test/parallel/test-http-response-close.js +++ b/test/parallel/test-http-response-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-response-no-headers.js b/test/parallel/test-http-response-no-headers.js index 5d18b6182cd785..888eb9ac4b87e2 100644 --- a/test/parallel/test-http-response-no-headers.js +++ b/test/parallel/test-http-response-no-headers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-response-readable.js b/test/parallel/test-http-response-readable.js index 0774b8ed9c963f..1f50137d7166fd 100644 --- a/test/parallel/test-http-response-readable.js +++ b/test/parallel/test-http-response-readable.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-response-status-message.js b/test/parallel/test-http-response-status-message.js index abbae8818bfecd..a1e1f15697e468 100644 --- a/test/parallel/test-http-response-status-message.js +++ b/test/parallel/test-http-response-status-message.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -6,15 +7,24 @@ var net = require('net'); var testsComplete = 0; var testCases = [ - { path: "/200", statusMessage: "OK", response: 'HTTP/1.1 200 OK\r\n\r\n' }, - { path: "/500", statusMessage: "Internal Server Error", response: 'HTTP/1.1 500 Internal Server Error\r\n\r\n' }, - { path: "/302", statusMessage: "Moved Temporarily", response: 'HTTP/1.1 302 Moved Temporarily\r\n\r\n' }, - { path: "/missing", statusMessage: "", response: 'HTTP/1.1 200 \r\n\r\n' }, - { path: "/missing-no-space", statusMessage: "", response: 'HTTP/1.1 200\r\n\r\n' } + { path: '/200', statusMessage: 'OK', + response: 'HTTP/1.1 200 OK\r\n\r\n' }, + { path: '/500', statusMessage: 'Internal Server Error', + response: 'HTTP/1.1 500 Internal Server Error\r\n\r\n' }, + { path: '/302', statusMessage: 'Moved Temporarily', + response: 'HTTP/1.1 302 Moved Temporarily\r\n\r\n' }, + { path: '/missing', statusMessage: '', + response: 'HTTP/1.1 200 \r\n\r\n' }, + { path: '/missing-no-space', statusMessage: '', + response: 'HTTP/1.1 200\r\n\r\n' } ]; testCases.findByPath = function(path) { - var matching = this.filter(function(testCase) { return testCase.path === path; }); - if (matching.length === 0) { throw "failed to find test case with path " + path; } + var matching = this.filter(function(testCase) { + return testCase.path === path; + }); + if (matching.length === 0) { + throw 'failed to find test case with path ' + path; + } return matching[0]; }; diff --git a/test/parallel/test-http-server-multiheaders.js b/test/parallel/test-http-server-multiheaders.js index ac5849d075ec40..440e10533787fd 100644 --- a/test/parallel/test-http-server-multiheaders.js +++ b/test/parallel/test-http-server-multiheaders.js @@ -1,3 +1,4 @@ +'use strict'; // Verify that the HTTP server implementation handles multiple instances // of the same header as per RFC2616: joining the handful of fields by ', ' // that support it, and dropping duplicates for other fields. diff --git a/test/parallel/test-http-server-multiheaders2.js b/test/parallel/test-http-server-multiheaders2.js index 5a3b80c5cd8823..438e8ba759e8ba 100644 --- a/test/parallel/test-http-server-multiheaders2.js +++ b/test/parallel/test-http-server-multiheaders2.js @@ -1,3 +1,4 @@ +'use strict'; // Verify that the HTTP server implementation handles multiple instances // of the same header as per RFC2616: joining the handful of fields by ', ' // that support it, and dropping duplicates for other fields. @@ -49,10 +50,12 @@ var multipleForbidden = [ var srv = http.createServer(function(req, res) { multipleForbidden.forEach(function(header) { - assert.equal(req.headers[header.toLowerCase()], 'foo', 'header parsed incorrectly: ' + header); + assert.equal(req.headers[header.toLowerCase()], + 'foo', 'header parsed incorrectly: ' + header); }); multipleAllowed.forEach(function(header) { - assert.equal(req.headers[header.toLowerCase()], 'foo, bar', 'header parsed incorrectly: ' + header); + assert.equal(req.headers[header.toLowerCase()], + 'foo, bar', 'header parsed incorrectly: ' + header); }); assert.equal(req.headers['content-length'], 0); @@ -65,7 +68,7 @@ var srv = http.createServer(function(req, res) { function makeHeader(value) { return function(header) { return [header, value]; - } + }; } var headers = [] diff --git a/test/parallel/test-http-server-stale-close.js b/test/parallel/test-http-server-stale-close.js index aa834b1fae3ef3..a866d39c2cc735 100644 --- a/test/parallel/test-http-server-stale-close.js +++ b/test/parallel/test-http-server-stale-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-server.js b/test/parallel/test-http-server.js index b96b57998a2cb6..9ba13ddf96b6ec 100644 --- a/test/parallel/test-http-server.js +++ b/test/parallel/test-http-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-set-cookies.js b/test/parallel/test-http-set-cookies.js index 1c03db01dba29e..9a43f82a39c12e 100644 --- a/test/parallel/test-http-set-cookies.js +++ b/test/parallel/test-http-set-cookies.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-set-timeout-server.js b/test/parallel/test-http-set-timeout-server.js index ccad6f1f3a398e..1f6c900da4f1a3 100644 --- a/test/parallel/test-http-set-timeout-server.js +++ b/test/parallel/test-http-set-timeout-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -16,8 +17,9 @@ function run() { if (fn) { console.log('# %s', fn.name); fn(run); - } else + } else { console.log('ok'); + } } test(function serverTimeout(cb) { diff --git a/test/parallel/test-http-set-timeout.js b/test/parallel/test-http-set-timeout.js index 1c547f06ee2200..be428d8970b27b 100644 --- a/test/parallel/test-http-set-timeout.js +++ b/test/parallel/test-http-set-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-set-trailers.js b/test/parallel/test-http-set-trailers.js index 98001afb66448f..6f5c02f5605969 100644 --- a/test/parallel/test-http-set-trailers.js +++ b/test/parallel/test-http-set-trailers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-should-keep-alive.js b/test/parallel/test-http-should-keep-alive.js index 3c2d2530833305..870223a37b6d44 100644 --- a/test/parallel/test-http-should-keep-alive.js +++ b/test/parallel/test-http-should-keep-alive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-status-code.js b/test/parallel/test-http-status-code.js index e862ed6076b447..19c36b0b2fd27f 100644 --- a/test/parallel/test-http-status-code.js +++ b/test/parallel/test-http-status-code.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-status-message.js b/test/parallel/test-http-status-message.js index 8d79d1a5affe4c..e579b8e995e120 100644 --- a/test/parallel/test-http-status-message.js +++ b/test/parallel/test-http-status-message.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-timeout-overflow.js b/test/parallel/test-http-timeout-overflow.js index b4d64e459bfc12..0df485edc93f9c 100644 --- a/test/parallel/test-http-timeout-overflow.js +++ b/test/parallel/test-http-timeout-overflow.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -14,7 +15,7 @@ var server = http.createServer(function(req, res) { }); server.listen(port, function() { - function callback(){} + function callback() {} var req = http.request({ port: port, @@ -26,7 +27,7 @@ server.listen(port, function() { res.on('end', function() { clientRequests++; server.close(); - }) + }); res.resume(); }); diff --git a/test/parallel/test-http-timeout.js b/test/parallel/test-http-timeout.js index 80393837f3201d..aab903420f0acc 100644 --- a/test/parallel/test-http-timeout.js +++ b/test/parallel/test-http-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -6,8 +7,8 @@ var http = require('http'); var port = common.PORT; var server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('OK'); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('OK'); }); var agent = new http.Agent({maxSockets: 1}); @@ -18,13 +19,13 @@ server.listen(port, function() { createRequest().end(); } - function callback(){} + function callback() {} var count = 0; function createRequest() { - var req = http.request({port: port, path: '/', agent: agent}, function(res) { - + var req = http.request({port: port, path: '/', agent: agent}, + function(res) { req.clearTimeout(callback); res.on('end', function() { @@ -33,7 +34,7 @@ server.listen(port, function() { if (count == 11) { server.close(); } - }) + }); res.resume(); }); diff --git a/test/parallel/test-http-unix-socket.js b/test/parallel/test-http-unix-socket.js index 1c13dafd3b038b..9ec8c8a1572844 100644 --- a/test/parallel/test-http-unix-socket.js +++ b/test/parallel/test-http-unix-socket.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-http-upgrade-agent.js b/test/parallel/test-http-upgrade-agent.js index b1655b7d0b41ae..84cfee90d528de 100644 --- a/test/parallel/test-http-upgrade-agent.js +++ b/test/parallel/test-http-upgrade-agent.js @@ -1,3 +1,4 @@ +'use strict'; // Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to // the HTTP client. This test uses a raw TCP server to better control server // behavior. diff --git a/test/parallel/test-http-upgrade-client.js b/test/parallel/test-http-upgrade-client.js index 14e0b9ca6a117d..b8ba033f2e01cb 100644 --- a/test/parallel/test-http-upgrade-client.js +++ b/test/parallel/test-http-upgrade-client.js @@ -1,3 +1,4 @@ +'use strict'; // Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to // the HTTP client. This test uses a raw TCP server to better control server // behavior. diff --git a/test/parallel/test-http-upgrade-client2.js b/test/parallel/test-http-upgrade-client2.js index d2b0f9c215b376..424d7c811c1a5a 100644 --- a/test/parallel/test-http-upgrade-client2.js +++ b/test/parallel/test-http-upgrade-client2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-upgrade-server.js b/test/parallel/test-http-upgrade-server.js index 84a8de9fed1b9a..9b34fe42eb05b9 100644 --- a/test/parallel/test-http-upgrade-server.js +++ b/test/parallel/test-http-upgrade-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-upgrade-server2.js b/test/parallel/test-http-upgrade-server2.js index 7af34c52719c4d..9a22df52c210be 100644 --- a/test/parallel/test-http-upgrade-server2.js +++ b/test/parallel/test-http-upgrade-server2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-url.parse-auth-with-header-in-request.js b/test/parallel/test-http-url.parse-auth-with-header-in-request.js index 9df0f5f6cda912..bb5de74ff9dcad 100644 --- a/test/parallel/test-http-url.parse-auth-with-header-in-request.js +++ b/test/parallel/test-http-url.parse-auth-with-header-in-request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-url.parse-auth.js b/test/parallel/test-http-url.parse-auth.js index 7038efb552b031..d06c79a9e707a4 100644 --- a/test/parallel/test-http-url.parse-auth.js +++ b/test/parallel/test-http-url.parse-auth.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-url.parse-basic.js b/test/parallel/test-http-url.parse-basic.js index 234082ad188b2a..efc375e97cbb62 100644 --- a/test/parallel/test-http-url.parse-basic.js +++ b/test/parallel/test-http-url.parse-basic.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-url.parse-https.request.js b/test/parallel/test-http-url.parse-https.request.js index 44287bc6b974dd..7fb749b069d140 100644 --- a/test/parallel/test-http-url.parse-https.request.js +++ b/test/parallel/test-http-url.parse-https.request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-url.parse-only-support-http-https-protocol.js b/test/parallel/test-http-url.parse-only-support-http-https-protocol.js index c8ae4ffeae97b2..5e49193181032c 100644 --- a/test/parallel/test-http-url.parse-only-support-http-https-protocol.js +++ b/test/parallel/test-http-url.parse-only-support-http-https-protocol.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -8,7 +9,8 @@ assert.throws(function() { http.request(url.parse('file:///whatever')); }, function(err) { if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "file:" not supported. Expected "http:".'); + assert.strictEqual(err.message, 'Protocol "file:" not supported.' + + ' Expected "http:".'); return true; } }); @@ -17,7 +19,8 @@ assert.throws(function() { http.request(url.parse('mailto:[email protected]')); }, function(err) { if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "mailto:" not supported. Expected "http:".'); + assert.strictEqual(err.message, 'Protocol "mailto:" not supported.' + + ' Expected "http:".'); return true; } }); @@ -26,7 +29,8 @@ assert.throws(function() { http.request(url.parse('ftp://www.example.com')); }, function(err) { if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "ftp:" not supported. Expected "http:".'); + assert.strictEqual(err.message, 'Protocol "ftp:" not supported.' + + ' Expected "http:".'); return true; } }); @@ -35,7 +39,8 @@ assert.throws(function() { http.request(url.parse('javascript:alert(\'hello\');')); }, function(err) { if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "javascript:" not supported. Expected "http:".'); + assert.strictEqual(err.message, 'Protocol "javascript:" not supported.' + + ' Expected "http:".'); return true; } }); @@ -44,7 +49,8 @@ assert.throws(function() { http.request(url.parse('xmpp:[email protected]')); }, function(err) { if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "xmpp:" not supported. Expected "http:".'); + assert.strictEqual(err.message, 'Protocol "xmpp:" not supported.' + + ' Expected "http:".'); return true; } }); @@ -53,7 +59,8 @@ assert.throws(function() { http.request(url.parse('f://some.host/path')); }, function(err) { if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "f:" not supported. Expected "http:".'); + assert.strictEqual(err.message, 'Protocol "f:" not supported.' + + ' Expected "http:".'); return true; } }); diff --git a/test/parallel/test-http-url.parse-path.js b/test/parallel/test-http-url.parse-path.js index 2ff78755c1ed39..087f535fa99c83 100644 --- a/test/parallel/test-http-url.parse-path.js +++ b/test/parallel/test-http-url.parse-path.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-url.parse-post.js b/test/parallel/test-http-url.parse-post.js index ae6a85da0ec395..b6a0fdeb255235 100644 --- a/test/parallel/test-http-url.parse-post.js +++ b/test/parallel/test-http-url.parse-post.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-url.parse-search.js b/test/parallel/test-http-url.parse-search.js index 16b65d2f94a3ea..04e5a72e8f913e 100644 --- a/test/parallel/test-http-url.parse-search.js +++ b/test/parallel/test-http-url.parse-search.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-wget.js b/test/parallel/test-http-wget.js index b79cf84078e157..78144ac6fbf7cb 100644 --- a/test/parallel/test-http-wget.js +++ b/test/parallel/test-http-wget.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-write-callbacks.js b/test/parallel/test-http-write-callbacks.js index a666e7ffe130a3..404396723e4416 100644 --- a/test/parallel/test-http-write-callbacks.js +++ b/test/parallel/test-http-write-callbacks.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-write-empty-string.js b/test/parallel/test-http-write-empty-string.js index e0ddbe3c22add4..50a9f5d509f381 100644 --- a/test/parallel/test-http-write-empty-string.js +++ b/test/parallel/test-http-write-empty-string.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-write-head.js b/test/parallel/test-http-write-head.js index acd2a6058dd526..79a8502c4f01b0 100644 --- a/test/parallel/test-http-write-head.js +++ b/test/parallel/test-http-write-head.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-zero-length-write.js b/test/parallel/test-http-zero-length-write.js index 583b081a522873..1ba29ca1c4a9fb 100644 --- a/test/parallel/test-http-zero-length-write.js +++ b/test/parallel/test-http-zero-length-write.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -22,7 +23,7 @@ function getSrc() { var chunks = [ '', 'asdf', '', 'foo', '', 'bar', '' ]; var interval = setInterval(function() { if (paused) - return + return; var chunk = chunks.shift(); if (chunk !== undefined) { diff --git a/test/parallel/test-http.js b/test/parallel/test-http.js index c1c55d2d525a34..daa746cdbe5b7a 100644 --- a/test/parallel/test-http.js +++ b/test/parallel/test-http.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-https-agent-servername.js b/test/parallel/test-https-agent-servername.js index 1647b0ee9a6ae8..5af9af9818008c 100644 --- a/test/parallel/test-https-agent-servername.js +++ b/test/parallel/test-https-agent-servername.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-agent.js b/test/parallel/test-https-agent.js index 15604f74e5fc75..a26882844e3e59 100644 --- a/test/parallel/test-https-agent.js +++ b/test/parallel/test-https-agent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-byteswritten.js b/test/parallel/test-https-byteswritten.js index 5c657b26076499..3e50b6f84dc265 100644 --- a/test/parallel/test-https-byteswritten.js +++ b/test/parallel/test-https-byteswritten.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-https-client-checkServerIdentity.js b/test/parallel/test-https-client-checkServerIdentity.js index c7bffc90002291..8f4aad7f5eff1e 100644 --- a/test/parallel/test-https-client-checkServerIdentity.js +++ b/test/parallel/test-https-client-checkServerIdentity.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -17,12 +18,12 @@ var options = { var reqCount = 0; -var server = https.createServer(options, function (req, res) { +var server = https.createServer(options, function(req, res) { ++reqCount; res.writeHead(200); res.end(); req.resume(); -}).listen(common.PORT, function () { +}).listen(common.PORT, function() { authorized(); }); @@ -31,10 +32,10 @@ function authorized() { port: common.PORT, rejectUnauthorized: true, ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))] - }, function (res) { + }, function(res) { assert(false); }); - req.on('error', function (err) { + req.on('error', function(err) { override(); }); req.end(); @@ -45,21 +46,21 @@ function override() { port: common.PORT, rejectUnauthorized: true, ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))], - checkServerIdentity: function (host, cert) { + checkServerIdentity: function(host, cert) { return false; } }; options.agent = new https.Agent(options); - var req = https.request(options, function (res) { + var req = https.request(options, function(res) { assert(req.socket.authorized); server.close(); }); - req.on('error', function (err) { + req.on('error', function(err) { throw err; }); req.end(); } -process.on('exit', function () { +process.on('exit', function() { assert.equal(reqCount, 1); }); diff --git a/test/parallel/test-https-client-get-url.js b/test/parallel/test-https-client-get-url.js index 01cea20242e710..66c11cd2db34db 100644 --- a/test/parallel/test-https-client-get-url.js +++ b/test/parallel/test-https-client-get-url.js @@ -1,3 +1,4 @@ +'use strict'; // disable strict server certificate validation by the client process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; diff --git a/test/parallel/test-https-client-reject.js b/test/parallel/test-https-client-reject.js index d3fcae7befebb4..55c335289d4131 100644 --- a/test/parallel/test-https-client-reject.js +++ b/test/parallel/test-https-client-reject.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-client-resume.js b/test/parallel/test-https-client-resume.js index 974db0f59775cf..024c5fa17f6038 100644 --- a/test/parallel/test-https-client-resume.js +++ b/test/parallel/test-https-client-resume.js @@ -1,3 +1,4 @@ +'use strict'; // Create an ssl server. First connection, validate that not resume. // Cache session and close connection. Use session on second connection. // ASSERT resumption. @@ -21,7 +22,7 @@ var options = { var connections = 0; // create server -var server = https.createServer(options, function(res, res) { +var server = https.createServer(options, function(req, res) { res.end('Goodbye'); connections++; }); diff --git a/test/parallel/test-https-connecting-to-http.js b/test/parallel/test-https-connecting-to-http.js index eb0ea40dc9c35a..64adb7760321bf 100644 --- a/test/parallel/test-https-connecting-to-http.js +++ b/test/parallel/test-https-connecting-to-http.js @@ -1,3 +1,4 @@ +'use strict'; // This tests the situation where you try to connect a https client // to an http server. You should get an error and exit. var common = require('../common'); diff --git a/test/parallel/test-https-drain.js b/test/parallel/test-https-drain.js index f2ea3fb4e44be2..0ce55b0849b585 100644 --- a/test/parallel/test-https-drain.js +++ b/test/parallel/test-https-drain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-eof-for-eom.js b/test/parallel/test-https-eof-for-eom.js index 14e087874e2285..78a2f3828cb9dd 100644 --- a/test/parallel/test-https-eof-for-eom.js +++ b/test/parallel/test-https-eof-for-eom.js @@ -1,3 +1,4 @@ +'use strict'; // I hate HTTP. One way of terminating an HTTP response is to not send // a content-length header, not send a transfer-encoding: chunked header, // and simply terminate the TCP connection. That is identity diff --git a/test/parallel/test-https-foafssl.js b/test/parallel/test-https-foafssl.js index 9d8d34dd791a75..f9b382ad830d35 100644 --- a/test/parallel/test-https-foafssl.js +++ b/test/parallel/test-https-foafssl.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.opensslCli) { diff --git a/test/parallel/test-https-host-headers.js b/test/parallel/test-https-host-headers.js index b8bcb407f1bebb..6a828d4aabbe07 100644 --- a/test/parallel/test-https-host-headers.js +++ b/test/parallel/test-https-host-headers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-localaddress-bind-error.js b/test/parallel/test-https-localaddress-bind-error.js index 153233f1a691fb..21e630dee43404 100644 --- a/test/parallel/test-https-localaddress-bind-error.js +++ b/test/parallel/test-https-localaddress-bind-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -17,7 +18,7 @@ var invalidLocalAddress = '1.2.3.4'; var gotError = false; var server = https.createServer(options, function(req, res) { - console.log("Connect from: " + req.connection.remoteAddress); + console.log('Connect from: ' + req.connection.remoteAddress); req.on('end', function() { res.writeHead(200, { 'Content-Type': 'text/plain' }); @@ -26,7 +27,7 @@ var server = https.createServer(options, function(req, res) { req.resume(); }); -server.listen(common.PORT, "127.0.0.1", function() { +server.listen(common.PORT, '127.0.0.1', function() { var req = https.request({ host: 'localhost', port: common.PORT, diff --git a/test/parallel/test-https-localaddress.js b/test/parallel/test-https-localaddress.js index b3b1d2cb942e07..0f3241c70b46ec 100644 --- a/test/parallel/test-https-localaddress.js +++ b/test/parallel/test-https-localaddress.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), fs = require('fs'), assert = require('assert'); @@ -18,8 +19,8 @@ var options = { cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = https.createServer(options, function (req, res) { - console.log("Connect from: " + req.connection.remoteAddress); +var server = https.createServer(options, function(req, res) { + console.log('Connect from: ' + req.connection.remoteAddress); assert.equal('127.0.0.2', req.connection.remoteAddress); req.on('end', function() { @@ -29,7 +30,7 @@ var server = https.createServer(options, function (req, res) { req.resume(); }); -server.listen(common.PORT, "127.0.0.1", function() { +server.listen(common.PORT, '127.0.0.1', function() { var options = { host: 'localhost', port: common.PORT, diff --git a/test/parallel/test-https-pfx.js b/test/parallel/test-https-pfx.js index 30dbea6ad0975e..f3968588333b44 100644 --- a/test/parallel/test-https-pfx.js +++ b/test/parallel/test-https-pfx.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -31,8 +32,8 @@ server.listen(options.port, options.host, function() { var data = ''; https.get(options, function(res) { - res.on('data', function(data_) { data += data_ }); - res.on('end', function() { server.close() }); + res.on('data', function(data_) { data += data_; }); + res.on('end', function() { server.close(); }); }); process.on('exit', function() { diff --git a/test/parallel/test-https-req-split.js b/test/parallel/test-https-req-split.js index 210363e430b9f1..4fd48eb16151fa 100644 --- a/test/parallel/test-https-req-split.js +++ b/test/parallel/test-https-req-split.js @@ -1,3 +1,4 @@ +'use strict'; // disable strict server certificate validation by the client process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; diff --git a/test/parallel/test-https-set-timeout-server.js b/test/parallel/test-https-set-timeout-server.js index 5ae8baee6940d7..2657b371e3c33b 100644 --- a/test/parallel/test-https-set-timeout-server.js +++ b/test/parallel/test-https-set-timeout-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -28,8 +29,9 @@ function run() { if (fn) { console.log('# %s', fn.name); fn(run); - } else + } else { console.log('ok'); + } } test(function serverTimeout(cb) { diff --git a/test/parallel/test-https-simple.js b/test/parallel/test-https-simple.js index 840838b83e4787..c2b93fdef855a0 100644 --- a/test/parallel/test-https-simple.js +++ b/test/parallel/test-https-simple.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-socket-options.js b/test/parallel/test-https-socket-options.js index eef94765a52bf1..52e46bd20b7807 100644 --- a/test/parallel/test-https-socket-options.js +++ b/test/parallel/test-https-socket-options.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -43,7 +44,8 @@ server_http.listen(common.PORT, function() { req.end(); }); -// Then try https server (requires functions to be mirroed in tls.js's CryptoStream) +// Then try https server (requires functions to be +// mirroed in tls.js's CryptoStream) var server_https = https.createServer(options, function(req, res) { console.log('got HTTPS request'); @@ -51,7 +53,7 @@ var server_https = https.createServer(options, function(req, res) { res.end(body); }); -server_https.listen(common.PORT+1, function() { +server_https.listen(common.PORT + 1, function() { var req = https.request({ port: common.PORT + 1, rejectUnauthorized: false diff --git a/test/parallel/test-https-strict.js b/test/parallel/test-https-strict.js index b2620fa88b236c..7ab5c3ee8200be 100644 --- a/test/parallel/test-https-strict.js +++ b/test/parallel/test-https-strict.js @@ -1,3 +1,4 @@ +'use strict'; // disable strict server certificate validation by the client process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; @@ -100,7 +101,7 @@ function listening() { if (listenWait === 0) { allListening(); } - } + }; } function makeReq(path, port, error, host, ca) { @@ -127,7 +128,7 @@ function makeReq(path, port, error, host, ca) { } if (host) { - options.headers = { host: host } + options.headers = { host: host }; } var req = https.get(options); expectResponseCount++; @@ -136,7 +137,7 @@ function makeReq(path, port, error, host, ca) { : port === port3 ? server3 : null; - if (!server) throw new Error('invalid port: '+port); + if (!server) throw new Error('invalid port: ' + port); server.expectCount++; req.on('response', function(res) { @@ -150,7 +151,7 @@ function makeReq(path, port, error, host, ca) { server3.close(); } res.resume(); - }) + }); } function allListening() { diff --git a/test/parallel/test-https-timeout-server-2.js b/test/parallel/test-https-timeout-server-2.js index d802ad4ae9b4a3..d39554fcb17124 100644 --- a/test/parallel/test-https-timeout-server-2.js +++ b/test/parallel/test-https-timeout-server-2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-timeout-server.js b/test/parallel/test-https-timeout-server.js index a24779ac7658b1..2707c30d181bf5 100644 --- a/test/parallel/test-https-timeout-server.js +++ b/test/parallel/test-https-timeout-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-timeout.js b/test/parallel/test-https-timeout.js index c03cb013d599b7..f6f1375180991c 100644 --- a/test/parallel/test-https-timeout.js +++ b/test/parallel/test-https-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-truncate.js b/test/parallel/test-https-truncate.js index 6a58bfe7715321..aba1be809abddd 100644 --- a/test/parallel/test-https-truncate.js +++ b/test/parallel/test-https-truncate.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-internal-modules-expose.js b/test/parallel/test-internal-modules-expose.js index 4ea79dbbf73512..4ece1d0c7b6f29 100644 --- a/test/parallel/test-internal-modules-expose.js +++ b/test/parallel/test-internal-modules-expose.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --expose_internals var common = require('../common'); diff --git a/test/parallel/test-internal-modules.js b/test/parallel/test-internal-modules.js index ebba2500d568b2..011b6f7132e9bf 100644 --- a/test/parallel/test-internal-modules.js +++ b/test/parallel/test-internal-modules.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-intl.js b/test/parallel/test-intl.js index 390155fc26e817..8701d90f7c0acc 100644 --- a/test/parallel/test-intl.js +++ b/test/parallel/test-intl.js @@ -1,10 +1,11 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); // does node think that i18n was enabled? var enablei18n = process.config.variables.v8_enable_i18n_support; if (enablei18n === undefined) { - enablei18n = false; + enablei18n = false; } // is the Intl object present? diff --git a/test/parallel/test-listen-fd-cluster.js b/test/parallel/test-listen-fd-cluster.js index 4b60a18161103c..c3ba42f315daba 100644 --- a/test/parallel/test-listen-fd-cluster.js +++ b/test/parallel/test-listen-fd-cluster.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -43,7 +44,7 @@ function test() { server: 'localhost', port: PORT, path: '/', - }).on('response', function (res) { + }).on('response', function(res) { var s = ''; res.on('data', function(c) { s += c.toString(); @@ -58,7 +59,7 @@ function test() { assert.equal(res.statusCode, 200); console.log('ok'); }); - }) + }); } } diff --git a/test/parallel/test-listen-fd-detached-inherit.js b/test/parallel/test-listen-fd-detached-inherit.js index 329eee5f818d48..7e8f7fbaf8a018 100644 --- a/test/parallel/test-listen-fd-detached-inherit.js +++ b/test/parallel/test-listen-fd-detached-inherit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -39,7 +40,7 @@ function test() { server: 'localhost', port: PORT, path: '/', - }).on('response', function (res) { + }).on('response', function(res) { var s = ''; res.on('data', function(c) { s += c.toString(); @@ -55,7 +56,7 @@ function test() { assert.equal(s, 'hello from child\n'); assert.equal(res.statusCode, 200); }); - }) + }); } } diff --git a/test/parallel/test-listen-fd-detached.js b/test/parallel/test-listen-fd-detached.js index a014fa1ee4a5a3..fceedfd25251dc 100644 --- a/test/parallel/test-listen-fd-detached.js +++ b/test/parallel/test-listen-fd-detached.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -39,7 +40,7 @@ function test() { server: 'localhost', port: PORT, path: '/', - }).on('response', function (res) { + }).on('response', function(res) { var s = ''; res.on('data', function(c) { s += c.toString(); @@ -55,7 +56,7 @@ function test() { assert.equal(s, 'hello from child\n'); assert.equal(res.statusCode, 200); }); - }) + }); } } diff --git a/test/parallel/test-listen-fd-ebadf.js b/test/parallel/test-listen-fd-ebadf.js index 628ece68a32023..db905dfa35e966 100644 --- a/test/parallel/test-listen-fd-ebadf.js +++ b/test/parallel/test-listen-fd-ebadf.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-listen-fd-server.js b/test/parallel/test-listen-fd-server.js index 39f15014a12851..b922c25ee10683 100644 --- a/test/parallel/test-listen-fd-server.js +++ b/test/parallel/test-listen-fd-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -39,7 +40,7 @@ function test() { server: 'localhost', port: PORT, path: '/', - }).on('response', function (res) { + }).on('response', function(res) { var s = ''; res.on('data', function(c) { s += c.toString(); @@ -55,7 +56,7 @@ function test() { assert.equal(s, 'hello from child\n'); assert.equal(res.statusCode, 200); }); - }) + }); } } diff --git a/test/parallel/test-memory-usage.js b/test/parallel/test-memory-usage.js index 4c1b67c83a324f..09dc4f820a8d74 100644 --- a/test/parallel/test-memory-usage.js +++ b/test/parallel/test-memory-usage.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-microtask-queue-integration-domain.js b/test/parallel/test-microtask-queue-integration-domain.js index 7e8b9a125038b4..7a4ad77cd321e3 100644 --- a/test/parallel/test-microtask-queue-integration-domain.js +++ b/test/parallel/test-microtask-queue-integration-domain.js @@ -1,12 +1,13 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); var implementations = [ - function (fn) { + function(fn) { Promise.resolve().then(fn); }, - function (fn) { + function(fn) { var obj = {}; Object.observe(obj, fn); @@ -18,20 +19,20 @@ var implementations = [ var expected = 0; var done = 0; -process.on('exit', function () { +process.on('exit', function() { assert.equal(done, expected); }); -function test (scheduleMicrotask) { +function test(scheduleMicrotask) { var nextTickCalled = false; expected++; - scheduleMicrotask(function () { - process.nextTick(function () { + scheduleMicrotask(function() { + process.nextTick(function() { nextTickCalled = true; }); - setTimeout(function () { + setTimeout(function() { assert(nextTickCalled); done++; }, 0); @@ -42,8 +43,8 @@ function test (scheduleMicrotask) { implementations.forEach(test); // tick callback case -setTimeout(function () { - implementations.forEach(function (impl) { +setTimeout(function() { + implementations.forEach(function(impl) { process.nextTick(test.bind(null, impl)); }); }, 0); diff --git a/test/parallel/test-microtask-queue-integration.js b/test/parallel/test-microtask-queue-integration.js index 3f68d736759f9e..37de5ee33b1477 100644 --- a/test/parallel/test-microtask-queue-integration.js +++ b/test/parallel/test-microtask-queue-integration.js @@ -1,11 +1,12 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var implementations = [ - function (fn) { + function(fn) { Promise.resolve().then(fn); }, - function (fn) { + function(fn) { var obj = {}; Object.observe(obj, fn); @@ -17,20 +18,20 @@ var implementations = [ var expected = 0; var done = 0; -process.on('exit', function () { +process.on('exit', function() { assert.equal(done, expected); }); -function test (scheduleMicrotask) { +function test(scheduleMicrotask) { var nextTickCalled = false; expected++; - scheduleMicrotask(function () { - process.nextTick(function () { + scheduleMicrotask(function() { + process.nextTick(function() { nextTickCalled = true; }); - setTimeout(function () { + setTimeout(function() { assert(nextTickCalled); done++; }, 0); @@ -41,8 +42,8 @@ function test (scheduleMicrotask) { implementations.forEach(test); // tick callback case -setTimeout(function () { - implementations.forEach(function (impl) { +setTimeout(function() { + implementations.forEach(function(impl) { process.nextTick(test.bind(null, impl)); }); }, 0); diff --git a/test/parallel/test-microtask-queue-run-domain.js b/test/parallel/test-microtask-queue-run-domain.js index 8627e90eff3518..77534920ff1451 100644 --- a/test/parallel/test-microtask-queue-run-domain.js +++ b/test/parallel/test-microtask-queue-run-domain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); diff --git a/test/parallel/test-microtask-queue-run-immediate-domain.js b/test/parallel/test-microtask-queue-run-immediate-domain.js index aa58b7fcb14710..2dea0a76cc1bf4 100644 --- a/test/parallel/test-microtask-queue-run-immediate-domain.js +++ b/test/parallel/test-microtask-queue-run-immediate-domain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); diff --git a/test/parallel/test-microtask-queue-run-immediate.js b/test/parallel/test-microtask-queue-run-immediate.js index fbce91e5179406..cfd9cd3659ef00 100644 --- a/test/parallel/test-microtask-queue-run-immediate.js +++ b/test/parallel/test-microtask-queue-run-immediate.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-microtask-queue-run.js b/test/parallel/test-microtask-queue-run.js index 73ba76efc49e0c..ca758546c2bcfd 100644 --- a/test/parallel/test-microtask-queue-run.js +++ b/test/parallel/test-microtask-queue-run.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-module-globalpaths-nodepath.js b/test/parallel/test-module-globalpaths-nodepath.js index d0261e81f7a802..2b991e0c28a674 100644 --- a/test/parallel/test-module-globalpaths-nodepath.js +++ b/test/parallel/test-module-globalpaths-nodepath.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-module-loading-error.js b/test/parallel/test-module-loading-error.js index 23eac7da6fbeeb..f33605d44ee949 100644 --- a/test/parallel/test-module-loading-error.js +++ b/test/parallel/test-module-loading-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-module-nodemodulepaths.js b/test/parallel/test-module-nodemodulepaths.js index e5e07dd40e3423..b1f04d41d0e092 100644 --- a/test/parallel/test-module-nodemodulepaths.js +++ b/test/parallel/test-module-nodemodulepaths.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -9,10 +10,10 @@ var file, delimiter, paths; if (isWindows) { file = 'C:\\Users\\Rocko Artischocko\\node_stuff\\foo'; - delimiter = '\\' + delimiter = '\\'; } else { file = '/usr/test/lib/node_modules/npm/foo'; - delimiter = '/' + delimiter = '/'; } paths = module._nodeModulePaths(file); diff --git a/test/parallel/test-net-after-close.js b/test/parallel/test-net-after-close.js index 99b213e0870238..223417111600a1 100644 --- a/test/parallel/test-net-after-close.js +++ b/test/parallel/test-net-after-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-better-error-messages-listen-path.js b/test/parallel/test-net-better-error-messages-listen-path.js index fcc3062a814f68..8a7e0220b36dfa 100644 --- a/test/parallel/test-net-better-error-messages-listen-path.js +++ b/test/parallel/test-net-better-error-messages-listen-path.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -5,5 +6,5 @@ var fp = '/blah/fadfa'; var server = net.createServer(assert.fail); server.listen(fp, assert.fail); server.on('error', common.mustCall(function(e) { - assert.equal(e.address, fp) + assert.equal(e.address, fp); })); diff --git a/test/parallel/test-net-better-error-messages-listen.js b/test/parallel/test-net-better-error-messages-listen.js index 9c7766bd4f4e3d..7e5fad925aeb92 100644 --- a/test/parallel/test-net-better-error-messages-listen.js +++ b/test/parallel/test-net-better-error-messages-listen.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-better-error-messages-path.js b/test/parallel/test-net-better-error-messages-path.js index dea4a10459edab..06cfecbd7c6af1 100644 --- a/test/parallel/test-net-better-error-messages-path.js +++ b/test/parallel/test-net-better-error-messages-path.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/parallel/test-net-better-error-messages-port-hostname.js b/test/parallel/test-net-better-error-messages-port-hostname.js index 3817dbb92ff1e2..9335f6b07a6625 100644 --- a/test/parallel/test-net-better-error-messages-port-hostname.js +++ b/test/parallel/test-net-better-error-messages-port-hostname.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/parallel/test-net-better-error-messages-port.js b/test/parallel/test-net-better-error-messages-port.js index a8c16a70385bb3..0f90089c0509fe 100644 --- a/test/parallel/test-net-better-error-messages-port.js +++ b/test/parallel/test-net-better-error-messages-port.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/parallel/test-net-binary.js b/test/parallel/test-net-binary.js index ae1a82ae8976bd..cf29cfe63bad71 100644 --- a/test/parallel/test-net-binary.js +++ b/test/parallel/test-net-binary.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-bind-twice.js b/test/parallel/test-net-bind-twice.js index ca75fb16fed9e9..ca4f554d30ca16 100644 --- a/test/parallel/test-net-bind-twice.js +++ b/test/parallel/test-net-bind-twice.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-buffersize.js b/test/parallel/test-net-buffersize.js index e8618beb7ac627..fcf0331c4ed500 100644 --- a/test/parallel/test-net-buffersize.js +++ b/test/parallel/test-net-buffersize.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-bytes-stats.js b/test/parallel/test-net-bytes-stats.js index 562e9b422c69c8..4e0a2e4001a452 100644 --- a/test/parallel/test-net-bytes-stats.js +++ b/test/parallel/test-net-bytes-stats.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-can-reset-timeout.js b/test/parallel/test-net-can-reset-timeout.js index 3febac8a3034f6..9fd7da4bb498ff 100644 --- a/test/parallel/test-net-can-reset-timeout.js +++ b/test/parallel/test-net-can-reset-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var net = require('net'); var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-connect-buffer.js b/test/parallel/test-net-connect-buffer.js index 74697932b0988b..304401f56ef50d 100644 --- a/test/parallel/test-net-connect-buffer.js +++ b/test/parallel/test-net-connect-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-connect-handle-econnrefused.js b/test/parallel/test-net-connect-handle-econnrefused.js index 77849b9b577261..0a8ce081680f76 100644 --- a/test/parallel/test-net-connect-handle-econnrefused.js +++ b/test/parallel/test-net-connect-handle-econnrefused.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/parallel/test-net-connect-immediate-finish.js b/test/parallel/test-net-connect-immediate-finish.js index 1fc908be1fba21..086cf910422372 100644 --- a/test/parallel/test-net-connect-immediate-finish.js +++ b/test/parallel/test-net-connect-immediate-finish.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-connect-options-ipv6.js b/test/parallel/test-net-connect-options-ipv6.js index 35af5124a46cd6..0ac1367ede1cce 100644 --- a/test/parallel/test-net-connect-options-ipv6.js +++ b/test/parallel/test-net-connect-options-ipv6.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-connect-options.js b/test/parallel/test-net-connect-options.js index fba35eab1c7b68..ac8bbcefc03e4c 100644 --- a/test/parallel/test-net-connect-options.js +++ b/test/parallel/test-net-connect-options.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-connect-paused-connection.js b/test/parallel/test-net-connect-paused-connection.js index 06e51f843fefad..60af9e44fb31f6 100644 --- a/test/parallel/test-net-connect-paused-connection.js +++ b/test/parallel/test-net-connect-paused-connection.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-net-create-connection.js b/test/parallel/test-net-create-connection.js index 9f468763c008b6..c245ddc2ae7860 100644 --- a/test/parallel/test-net-create-connection.js +++ b/test/parallel/test-net-create-connection.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -22,7 +23,7 @@ server.listen(tcpPort, 'localhost', function() { function fail(opts, errtype, msg) { assert.throws(function() { var client = net.createConnection(opts, cb); - }, function (err) { + }, function(err) { return err instanceof errtype && msg === err.message; }); } diff --git a/test/parallel/test-net-dns-error.js b/test/parallel/test-net-dns-error.js index 18f6fe259b75ec..17f251cec3b6af 100644 --- a/test/parallel/test-net-dns-error.js +++ b/test/parallel/test-net-dns-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-dns-lookup.js b/test/parallel/test-net-dns-lookup.js index e7c058fe144a56..18a80501185871 100644 --- a/test/parallel/test-net-dns-lookup.js +++ b/test/parallel/test-net-dns-lookup.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-during-close.js b/test/parallel/test-net-during-close.js index b2f139cfa0a1f8..a2fd424e0e83c0 100644 --- a/test/parallel/test-net-during-close.js +++ b/test/parallel/test-net-during-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-eaddrinuse.js b/test/parallel/test-net-eaddrinuse.js index 209e4909c49728..c1797b7369d5ed 100644 --- a/test/parallel/test-net-eaddrinuse.js +++ b/test/parallel/test-net-eaddrinuse.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-end-without-connect.js b/test/parallel/test-net-end-without-connect.js index 6ccf2b028082d2..2911591f9f486d 100644 --- a/test/parallel/test-net-end-without-connect.js +++ b/test/parallel/test-net-end-without-connect.js @@ -1,5 +1,6 @@ +'use strict'; var common = require('../common'); var net = require('net'); -var sock = new net.Socket; +var sock = new net.Socket(); sock.end(); // Should not throw. diff --git a/test/parallel/test-net-error-twice.js b/test/parallel/test-net-error-twice.js index 1620bb8ee55fa1..af92ca93206f18 100644 --- a/test/parallel/test-net-error-twice.js +++ b/test/parallel/test-net-error-twice.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -10,18 +11,18 @@ var errs = []; var srv = net.createServer(function onConnection(conn) { conn.write(buf); - conn.on('error', function (err) { + conn.on('error', function(err) { errs.push(err); if (errs.length > 1 && errs[0] === errs[1]) - assert(false, "We should not be emitting the same error twice"); + assert(false, 'We should not be emitting the same error twice'); }); conn.on('close', function() { srv.unref(); }); -}).listen(common.PORT, function () { +}).listen(common.PORT, function() { var client = net.connect({ port: common.PORT }); - client.on('connect', function () { + client.on('connect', function() { client.destroy(); }); }); diff --git a/test/parallel/test-net-isip.js b/test/parallel/test-net-isip.js index 1947810b82deb8..96177122b7ba21 100644 --- a/test/parallel/test-net-isip.js +++ b/test/parallel/test-net-isip.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -29,7 +30,7 @@ assert.equal(net.isIP('::'), 6); assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:12345:0000'), 0); assert.equal(net.isIP('0'), 0); assert.equal(net.isIP(), 0); -assert.equal(net.isIP(""), 0); +assert.equal(net.isIP(''), 0); assert.equal(net.isIPv4('127.0.0.1'), true); assert.equal(net.isIPv4('example.com'), false); diff --git a/test/parallel/test-net-keepalive.js b/test/parallel/test-net-keepalive.js index f5299c9eb34c0e..3c339f7abaa350 100644 --- a/test/parallel/test-net-keepalive.js +++ b/test/parallel/test-net-keepalive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-large-string.js b/test/parallel/test-net-large-string.js index 318f25a1c9a1e2..387f3f4f8c1dd3 100644 --- a/test/parallel/test-net-large-string.js +++ b/test/parallel/test-net-large-string.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-listen-close-server-callback-is-not-function.js b/test/parallel/test-net-listen-close-server-callback-is-not-function.js index f4eff779406e0f..7450cb16fc7943 100644 --- a/test/parallel/test-net-listen-close-server-callback-is-not-function.js +++ b/test/parallel/test-net-listen-close-server-callback-is-not-function.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var net = require('net'); diff --git a/test/parallel/test-net-listen-close-server.js b/test/parallel/test-net-listen-close-server.js index e3a73e6ae5cb60..9c4dbcfe2e15e2 100644 --- a/test/parallel/test-net-listen-close-server.js +++ b/test/parallel/test-net-listen-close-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-listen-error.js b/test/parallel/test-net-listen-error.js index 0ed2421fdfbca9..b0d8aac8f816e3 100644 --- a/test/parallel/test-net-listen-error.js +++ b/test/parallel/test-net-listen-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-listen-fd0.js b/test/parallel/test-net-listen-fd0.js index 7cfd49dbdd3d27..bf437268c92945 100644 --- a/test/parallel/test-net-listen-fd0.js +++ b/test/parallel/test-net-listen-fd0.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -14,6 +15,6 @@ net.createServer(assert.fail).listen({fd:0}).on('error', function(e) { case 'EINVAL': case 'ENOTSOCK': gotError = e; - break + break; } }); diff --git a/test/parallel/test-net-listen-port-option.js b/test/parallel/test-net-listen-port-option.js index 1b9938f7c7f155..d1eddb6707c274 100644 --- a/test/parallel/test-net-listen-port-option.js +++ b/test/parallel/test-net-listen-port-option.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-listen-shared-ports.js b/test/parallel/test-net-listen-shared-ports.js index 3139dc7ac29365..2062dd0ce136bb 100644 --- a/test/parallel/test-net-listen-shared-ports.js +++ b/test/parallel/test-net-listen-shared-ports.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-net-local-address-port.js b/test/parallel/test-net-local-address-port.js index 0bbfee80211d0c..aa28d180dae6ff 100644 --- a/test/parallel/test-net-local-address-port.js +++ b/test/parallel/test-net-local-address-port.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-localerror.js b/test/parallel/test-net-localerror.js index c2ef96165a6e70..45ec1fc9099955 100644 --- a/test/parallel/test-net-localerror.js +++ b/test/parallel/test-net-localerror.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-pause-resume-connecting.js b/test/parallel/test-net-pause-resume-connecting.js index b692f3508529e1..fb3b66c8cf991c 100644 --- a/test/parallel/test-net-pause-resume-connecting.js +++ b/test/parallel/test-net-pause-resume-connecting.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), net = require('net'); diff --git a/test/parallel/test-net-pingpong.js b/test/parallel/test-net-pingpong.js index 7a05591caf969b..9a0c8af5b0697d 100644 --- a/test/parallel/test-net-pingpong.js +++ b/test/parallel/test-net-pingpong.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-pipe-connect-errors.js b/test/parallel/test-net-pipe-connect-errors.js index 5150c6de819787..a831b107122c8d 100644 --- a/test/parallel/test-net-pipe-connect-errors.js +++ b/test/parallel/test-net-pipe-connect-errors.js @@ -1,3 +1,4 @@ +'use strict'; var fs = require('fs'); var net = require('net'); var path = require('path'); diff --git a/test/parallel/test-net-reconnect-error.js b/test/parallel/test-net-reconnect-error.js index 541a481fe12705..ed889829ec8abe 100644 --- a/test/parallel/test-net-reconnect-error.js +++ b/test/parallel/test-net-reconnect-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/parallel/test-net-reconnect.js b/test/parallel/test-net-reconnect.js index d65efac998102b..b2e8f6ea8b4e3f 100644 --- a/test/parallel/test-net-reconnect.js +++ b/test/parallel/test-net-reconnect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-remote-address-port.js b/test/parallel/test-net-remote-address-port.js index 2f8c673b57ef98..11d753ea460b79 100644 --- a/test/parallel/test-net-remote-address-port.js +++ b/test/parallel/test-net-remote-address-port.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-server-close.js b/test/parallel/test-net-server-close.js index 4101baf166b555..446b835a4c67df 100644 --- a/test/parallel/test-net-server-close.js +++ b/test/parallel/test-net-server-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -23,7 +24,7 @@ var server = net.createServer(function(c) { if (sockets.length === 2) { server.close(); - sockets.forEach(function(c) { c.destroy() }); + sockets.forEach(function(c) { c.destroy(); }); } }); diff --git a/test/parallel/test-net-server-connections.js b/test/parallel/test-net-server-connections.js index 76e9c2af1cc97f..138a78defb260d 100644 --- a/test/parallel/test-net-server-connections.js +++ b/test/parallel/test-net-server-connections.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-server-listen-remove-callback.js b/test/parallel/test-net-server-listen-remove-callback.js index d9a5a8bdec4934..a7d54081a6bb03 100644 --- a/test/parallel/test-net-server-listen-remove-callback.js +++ b/test/parallel/test-net-server-listen-remove-callback.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-server-max-connections.js b/test/parallel/test-net-server-max-connections.js index ea89bd9d9b04a9..3b425ba3358fb5 100644 --- a/test/parallel/test-net-server-max-connections.js +++ b/test/parallel/test-net-server-max-connections.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-server-pause-on-connect.js b/test/parallel/test-net-server-pause-on-connect.js index 0f47565f0098d0..db57114302f490 100644 --- a/test/parallel/test-net-server-pause-on-connect.js +++ b/test/parallel/test-net-server-pause-on-connect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-server-try-ports.js b/test/parallel/test-net-server-try-ports.js index 698cbcfa23e7c6..65cd5887a1356d 100644 --- a/test/parallel/test-net-server-try-ports.js +++ b/test/parallel/test-net-server-try-ports.js @@ -1,3 +1,4 @@ +'use strict'; // This tests binds to one port, then attempts to start a server on that // port. It should be EADDRINUSE but be able to then bind to another port. var common = require('../common'); diff --git a/test/parallel/test-net-server-unref-persistent.js b/test/parallel/test-net-server-unref-persistent.js index 3a5092b92e0b8f..a071b625ef26d7 100644 --- a/test/parallel/test-net-server-unref-persistent.js +++ b/test/parallel/test-net-server-unref-persistent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-server-unref.js b/test/parallel/test-net-server-unref.js index 2365864d6b41f3..98e95d6f105a84 100644 --- a/test/parallel/test-net-server-unref.js +++ b/test/parallel/test-net-server-unref.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-settimeout.js b/test/parallel/test-net-settimeout.js index 28943a1ef0c96b..61c0a90341716e 100644 --- a/test/parallel/test-net-settimeout.js +++ b/test/parallel/test-net-settimeout.js @@ -1,3 +1,4 @@ +'use strict'; // This example sets a timeout then immediately attempts to disable the timeout // https://github.com/joyent/node/pull/2245 diff --git a/test/parallel/test-net-socket-destroy-twice.js b/test/parallel/test-net-socket-destroy-twice.js index 2782048bd521c7..f23a70abb2c9a0 100644 --- a/test/parallel/test-net-socket-destroy-twice.js +++ b/test/parallel/test-net-socket-destroy-twice.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-socket-timeout-unref.js b/test/parallel/test-net-socket-timeout-unref.js index 16bdcecaf17e78..c7e651afef015f 100644 --- a/test/parallel/test-net-socket-timeout-unref.js +++ b/test/parallel/test-net-socket-timeout-unref.js @@ -1,8 +1,9 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); -var server = net.createServer(function (c) { +var server = net.createServer(function(c) { c.write('hello'); c.unref(); }); @@ -11,9 +12,9 @@ server.unref(); var timedout = false; -[8, 5, 3, 6, 2, 4].forEach(function (T) { +[8, 5, 3, 6, 2, 4].forEach(function(T) { var socket = net.createConnection(common.PORT, 'localhost'); - socket.setTimeout(T * 1000, function () { + socket.setTimeout(T * 1000, function() { console.log(process._getActiveHandles()); timedout = true; socket.destroy(); @@ -21,6 +22,7 @@ var timedout = false; socket.unref(); }); -process.on('exit', function () { - assert.strictEqual(timedout, false, 'Socket timeout should not hold loop open'); +process.on('exit', function() { + assert.strictEqual(timedout, false, + 'Socket timeout should not hold loop open'); }); diff --git a/test/parallel/test-net-socket-timeout.js b/test/parallel/test-net-socket-timeout.js index f4038298763e8d..5ab11909b4c306 100644 --- a/test/parallel/test-net-socket-timeout.js +++ b/test/parallel/test-net-socket-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/parallel/test-net-stream.js b/test/parallel/test-net-stream.js index 8f7efd45f6d18d..151b1b178f9adc 100644 --- a/test/parallel/test-net-stream.js +++ b/test/parallel/test-net-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -29,7 +30,7 @@ var server = net.createServer(function(socket) { socket.destroy(); }).on('close', function() { server.close(); - }) + }); for (var i = 0; i < N; ++i) { socket.write(buf, function() { }); diff --git a/test/parallel/test-net-write-after-close.js b/test/parallel/test-net-write-after-close.js index aaec89874674f3..b9516b839263cf 100644 --- a/test/parallel/test-net-write-after-close.js +++ b/test/parallel/test-net-write-after-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-write-connect-write.js b/test/parallel/test-net-write-connect-write.js index fbf6b51e6a1f5c..17b1b576d188be 100644 --- a/test/parallel/test-net-write-connect-write.js +++ b/test/parallel/test-net-write-connect-write.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-write-slow.js b/test/parallel/test-net-write-slow.js index 0b1cf4f5b2c9a5..4b8163984f556a 100644 --- a/test/parallel/test-net-write-slow.js +++ b/test/parallel/test-net-write-slow.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-next-tick-doesnt-hang.js b/test/parallel/test-next-tick-doesnt-hang.js index 7364b2f974d128..5e63463d4d1f94 100644 --- a/test/parallel/test-next-tick-doesnt-hang.js +++ b/test/parallel/test-next-tick-doesnt-hang.js @@ -1,3 +1,4 @@ +'use strict'; /* * This test verifies that having a single nextTick statement and nothing else * does not hang the event loop. If this test times out it has failed. diff --git a/test/parallel/test-next-tick-domain.js b/test/parallel/test-next-tick-domain.js index b07d741f65264f..4d53bba6c4f5cc 100644 --- a/test/parallel/test-next-tick-domain.js +++ b/test/parallel/test-next-tick-domain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -5,4 +6,5 @@ var origNextTick = process.nextTick; require('domain'); -assert.strictEqual(origNextTick, process.nextTick, 'Requiring domain should not change nextTick'); +assert.strictEqual(origNextTick, process.nextTick, + 'Requiring domain should not change nextTick'); diff --git a/test/parallel/test-next-tick-errors.js b/test/parallel/test-next-tick-errors.js index c2e635d5c5bd5c..eccd7a43a0825f 100644 --- a/test/parallel/test-next-tick-errors.js +++ b/test/parallel/test-next-tick-errors.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-next-tick-intentional-starvation.js b/test/parallel/test-next-tick-intentional-starvation.js index 5c8b414dcfead9..d4a8a1b7481329 100644 --- a/test/parallel/test-next-tick-intentional-starvation.js +++ b/test/parallel/test-next-tick-intentional-starvation.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-next-tick-ordering.js b/test/parallel/test-next-tick-ordering.js index 4340736aefec35..c2b936a1061d52 100644 --- a/test/parallel/test-next-tick-ordering.js +++ b/test/parallel/test-next-tick-ordering.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var i; diff --git a/test/parallel/test-next-tick-ordering2.js b/test/parallel/test-next-tick-ordering2.js index 69d4897fdbf9d2..4252d623679f65 100644 --- a/test/parallel/test-next-tick-ordering2.js +++ b/test/parallel/test-next-tick-ordering2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-next-tick.js b/test/parallel/test-next-tick.js index 1081a96fa2e35d..54e7b88cf022ca 100644 --- a/test/parallel/test-next-tick.js +++ b/test/parallel/test-next-tick.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-os.js b/test/parallel/test-os.js index ae57353435333a..2cbc851015429e 100644 --- a/test/parallel/test-os.js +++ b/test/parallel/test-os.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var os = require('os'); diff --git a/test/parallel/test-path-makelong.js b/test/parallel/test-path-makelong.js index 51d6404c4d4385..b9cc116a5ed90e 100644 --- a/test/parallel/test-path-makelong.js +++ b/test/parallel/test-path-makelong.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var path = require('path'); var common = require('../common'); diff --git a/test/parallel/test-path-parse-format.js b/test/parallel/test-path-parse-format.js index d31dc995720030..37f37fc9b57c17 100644 --- a/test/parallel/test-path-parse-format.js +++ b/test/parallel/test-path-parse-format.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var path = require('path'); @@ -30,18 +31,30 @@ var unixPaths = [ ]; var errors = [ - {method: 'parse', input: [null], message: /Path must be a string. Received null/}, - {method: 'parse', input: [{}], message: /Path must be a string. Received {}/}, - {method: 'parse', input: [true], message: /Path must be a string. Received true/}, - {method: 'parse', input: [1], message: /Path must be a string. Received 1/}, - {method: 'parse', input: [], message: /Path must be a string. Received undefined/}, - // {method: 'parse', input: [''], message: /Invalid path/}, // omitted because it's hard to trigger! - {method: 'format', input: [null], message: /Parameter 'pathObject' must be an object, not/}, - {method: 'format', input: [''], message: /Parameter 'pathObject' must be an object, not string/}, - {method: 'format', input: [true], message: /Parameter 'pathObject' must be an object, not boolean/}, - {method: 'format', input: [1], message: /Parameter 'pathObject' must be an object, not number/}, - {method: 'format', input: [{root: true}], message: /'pathObject.root' must be a string or undefined, not boolean/}, - {method: 'format', input: [{root: 12}], message: /'pathObject.root' must be a string or undefined, not number/}, + {method: 'parse', input: [null], + message: /Path must be a string. Received null/}, + {method: 'parse', input: [{}], + message: /Path must be a string. Received {}/}, + {method: 'parse', input: [true], + message: /Path must be a string. Received true/}, + {method: 'parse', input: [1], + message: /Path must be a string. Received 1/}, + {method: 'parse', input: [], + message: /Path must be a string. Received undefined/}, + // {method: 'parse', input: [''], + // message: /Invalid path/}, // omitted because it's hard to trigger! + {method: 'format', input: [null], + message: /Parameter 'pathObject' must be an object, not/}, + {method: 'format', input: [''], + message: /Parameter 'pathObject' must be an object, not string/}, + {method: 'format', input: [true], + message: /Parameter 'pathObject' must be an object, not boolean/}, + {method: 'format', input: [1], + message: /Parameter 'pathObject' must be an object, not number/}, + {method: 'format', input: [{root: true}], + message: /'pathObject.root' must be a string or undefined, not boolean/}, + {method: 'format', input: [{root: 12}], + message: /'pathObject.root' must be a string or undefined, not number/}, ]; check(path.win32, winPaths); diff --git a/test/parallel/test-path.js b/test/parallel/test-path.js index e0e9c5d5671e4e..b1209d762a53d3 100644 --- a/test/parallel/test-path.js +++ b/test/parallel/test-path.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-pipe-file-to-http.js b/test/parallel/test-pipe-file-to-http.js index 01c23cb418e426..12ce742c905bba 100644 --- a/test/parallel/test-pipe-file-to-http.js +++ b/test/parallel/test-pipe-file-to-http.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-pipe-return-val.js b/test/parallel/test-pipe-return-val.js index 6a333584f8f315..718d052cd24c27 100644 --- a/test/parallel/test-pipe-return-val.js +++ b/test/parallel/test-pipe-return-val.js @@ -1,3 +1,4 @@ +'use strict'; // This test ensures SourceStream.pipe(DestStream) returns DestStream var common = require('../common'); diff --git a/test/parallel/test-preload.js b/test/parallel/test-preload.js index 643edfb1d970cc..08657bbfb63a5e 100644 --- a/test/parallel/test-preload.js +++ b/test/parallel/test-preload.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), path = require('path'), @@ -12,15 +13,15 @@ var preloadOption = function(preloads) { option += '-r ' + preload + ' '; }); return option; -} +}; var fixture = function(name) { return path.join(__dirname, '../fixtures/' + name); -} +}; var fixtureA = fixture('printA.js'); var fixtureB = fixture('printB.js'); -var fixtureC = fixture('printC.js') +var fixtureC = fixture('printC.js'); var fixtureThrows = fixture('throws_error4.js'); // test preloading a single module works @@ -80,3 +81,15 @@ child_process.exec(nodeBinary + ' ' if (err) throw err; assert.ok(/worker terminated with code 43/.test(stdout)); }); + +// https://github.com/iojs/io.js/issues/1691 +var originalCwd = process.cwd(); +process.chdir(path.join(__dirname, '../fixtures/')); +child_process.exec(nodeBinary + ' ' + + '--expose_debug_as=v8debug ' + + '--require ' + fixture('cluster-preload.js') + ' ' + + 'cluster-preload-test.js', + function(err, stdout, stderr) { + if (err) throw err; + assert.ok(/worker terminated with code 43/.test(stdout)); + }); diff --git a/test/parallel/test-process-argv-0.js b/test/parallel/test-process-argv-0.js index daf8cb60ebff0d..4bdb7ac3e71971 100644 --- a/test/parallel/test-process-argv-0.js +++ b/test/parallel/test-process-argv-0.js @@ -1,3 +1,4 @@ +'use strict'; var util = require('util'); var path = require('path'); var assert = require('assert'); @@ -7,8 +8,8 @@ var common = require('../common'); console.error('argv=%j', process.argv); console.error('exec=%j', process.execPath); -if (process.argv[2] !== "child") { - var child = spawn('./iojs', [__filename, "child"], { +if (process.argv[2] !== 'child') { + var child = spawn('./iojs', [__filename, 'child'], { cwd: path.dirname(process.execPath) }); @@ -20,7 +21,7 @@ if (process.argv[2] !== "child") { child.stderr.on('data', function(chunk) { childErr += chunk; }); - child.on('exit', function () { + child.on('exit', function() { console.error('CHILD: %s', childErr.trim().split('\n').join('\nCHILD: ')); assert.equal(childArgv0, process.execPath); }); diff --git a/test/parallel/test-process-before-exit.js b/test/parallel/test-process-before-exit.js index 48639c249ddec1..eff96da98e4729 100644 --- a/test/parallel/test-process-before-exit.js +++ b/test/parallel/test-process-before-exit.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-process-binding.js b/test/parallel/test-process-binding.js index c803a8083f22b4..dad2816d40c185 100644 --- a/test/parallel/test-process-binding.js +++ b/test/parallel/test-process-binding.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); assert.throws( @@ -7,10 +8,10 @@ assert.throws( /No such module: test/ ); -assert.doesNotThrow(function () { +assert.doesNotThrow(function() { process.binding('buffer'); }, function(err) { if ( (err instanceof Error) ) { return true; } -}, "unexpected error"); +}, 'unexpected error'); diff --git a/test/parallel/test-process-config.js b/test/parallel/test-process-config.js index d9260ca94d6ff3..4fc3bcaa98afc8 100644 --- a/test/parallel/test-process-config.js +++ b/test/parallel/test-process-config.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-process-env.js b/test/parallel/test-process-env.js index f3e2957ba621a7..7e927d09bae668 100644 --- a/test/parallel/test-process-env.js +++ b/test/parallel/test-process-env.js @@ -1,3 +1,6 @@ +'use strict'; +/* eslint-disable max-len */ + // first things first, set the timezone; see tzset(3) process.env.TZ = 'Europe/Amsterdam'; diff --git a/test/parallel/test-process-exec-argv.js b/test/parallel/test-process-exec-argv.js index 7344000739576e..59c4264ee3c8b7 100644 --- a/test/parallel/test-process-exec-argv.js +++ b/test/parallel/test-process-exec-argv.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var spawn = require('child_process').spawn; @@ -9,11 +10,11 @@ if (process.argv[2] === 'child') { var child = spawn(process.execPath, execArgv.concat(args)); var out = ''; - child.stdout.on('data', function (chunk) { + child.stdout.on('data', function(chunk) { out += chunk; }); - child.on('exit', function () { + child.on('exit', function() { assert.deepEqual(JSON.parse(out), execArgv); }); } diff --git a/test/parallel/test-process-exit-code.js b/test/parallel/test-process-exit-code.js index 610cf662987850..fea8c2d4fcdc5d 100644 --- a/test/parallel/test-process-exit-code.js +++ b/test/parallel/test-process-exit-code.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-process-exit-from-before-exit.js b/test/parallel/test-process-exit-from-before-exit.js index e222f35245fb7d..30d358cb76da9d 100644 --- a/test/parallel/test-process-exit-from-before-exit.js +++ b/test/parallel/test-process-exit-from-before-exit.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-process-exit-recursive.js b/test/parallel/test-process-exit-recursive.js index a326ec7f630e8c..c1ee13370b26ca 100644 --- a/test/parallel/test-process-exit-recursive.js +++ b/test/parallel/test-process-exit-recursive.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); // recursively calling .exit() should not overflow the call stack diff --git a/test/parallel/test-process-exit.js b/test/parallel/test-process-exit.js index 58d7a276996c3c..999eefc1eff518 100644 --- a/test/parallel/test-process-exit.js +++ b/test/parallel/test-process-exit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-process-getgroups.js b/test/parallel/test-process-getgroups.js index f7c80ca6e02003..1cb5f38c1db203 100644 --- a/test/parallel/test-process-getgroups.js +++ b/test/parallel/test-process-getgroups.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; diff --git a/test/parallel/test-process-hrtime.js b/test/parallel/test-process-hrtime.js index c845f919bb2efd..0e2c5b110e9292 100644 --- a/test/parallel/test-process-hrtime.js +++ b/test/parallel/test-process-hrtime.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -18,7 +19,7 @@ assert.throws(function() { function validateTuple(tuple) { assert(Array.isArray(tuple)); assert.equal(2, tuple.length); - tuple.forEach(function (v) { + tuple.forEach(function(v) { assert.equal('number', typeof v); assert(isFinite(v)); }); diff --git a/test/parallel/test-process-kill-null.js b/test/parallel/test-process-kill-null.js index 77e2a8bb5ee5cb..65dab752f12e6d 100644 --- a/test/parallel/test-process-kill-null.js +++ b/test/parallel/test-process-kill-null.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-process-kill-pid.js b/test/parallel/test-process-kill-pid.js index 22ec5a68145961..f193e979166da7 100644 --- a/test/parallel/test-process-kill-pid.js +++ b/test/parallel/test-process-kill-pid.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -20,8 +21,8 @@ assert.throws(function() { process.kill('SIGTERM'); }, TypeError); assert.throws(function() { process.kill(null); }, TypeError); assert.throws(function() { process.kill(undefined); }, TypeError); assert.throws(function() { process.kill(+'not a number'); }, TypeError); -assert.throws(function() { process.kill(1/0); }, TypeError); -assert.throws(function() { process.kill(-1/0); }, TypeError); +assert.throws(function() { process.kill(1 / 0); }, TypeError); +assert.throws(function() { process.kill(-1 / 0); }, TypeError); // Test kill argument processing in valid cases. // diff --git a/test/parallel/test-process-next-tick.js b/test/parallel/test-process-next-tick.js index 3b2d37ef68a3be..e7b5f8f3fe886e 100644 --- a/test/parallel/test-process-next-tick.js +++ b/test/parallel/test-process-next-tick.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var N = 2; diff --git a/test/parallel/test-process-raw-debug.js b/test/parallel/test-process-raw-debug.js index 2264e59937517b..f849457d643894 100644 --- a/test/parallel/test-process-raw-debug.js +++ b/test/parallel/test-process-raw-debug.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var os = require('os'); diff --git a/test/parallel/test-process-remove-all-signal-listeners.js b/test/parallel/test-process-remove-all-signal-listeners.js index e5dd5a13a16fca..408f6596c4419e 100644 --- a/test/parallel/test-process-remove-all-signal-listeners.js +++ b/test/parallel/test-process-remove-all-signal-listeners.js @@ -1,3 +1,4 @@ +'use strict'; if (process.platform === 'win32') { // Win32 doesn't have signals, just a kindof emulation, insufficient // for this test to apply. diff --git a/test/parallel/test-process-versions.js b/test/parallel/test-process-versions.js index c3159789cefeae..637ada7fa8e349 100644 --- a/test/parallel/test-process-versions.js +++ b/test/parallel/test-process-versions.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-process-wrap.js b/test/parallel/test-process-wrap.js index f3d903adb11448..bf3dfe4e8b1651 100644 --- a/test/parallel/test-process-wrap.js +++ b/test/parallel/test-process-wrap.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Process = process.binding('process_wrap').Process; diff --git a/test/parallel/test-promises-unhandled-rejections.js b/test/parallel/test-promises-unhandled-rejections.js index 997d147a6dcc34..9a186de8dfec79 100644 --- a/test/parallel/test-promises-unhandled-rejections.js +++ b/test/parallel/test-promises-unhandled-rejections.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); @@ -105,7 +106,8 @@ function onUnhandledFail(done) { }, 10); } -asyncTest('synchronously rejected promise should trigger unhandledRejection', function(done) { +asyncTest('synchronously rejected promise should trigger' + + ' unhandledRejection', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -113,7 +115,8 @@ asyncTest('synchronously rejected promise should trigger unhandledRejection', fu Promise.reject(e); }); -asyncTest('synchronously rejected promise should trigger unhandledRejection', function(done) { +asyncTest('synchronously rejected promise should trigger' + + ' unhandledRejection', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -123,7 +126,8 @@ asyncTest('synchronously rejected promise should trigger unhandledRejection', fu }); }); -asyncTest('Promise rejected after setImmediate should trigger unhandledRejection', function(done) { +asyncTest('Promise rejected after setImmediate should trigger' + + ' unhandledRejection', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -135,7 +139,8 @@ asyncTest('Promise rejected after setImmediate should trigger unhandledRejection }); }); -asyncTest('Promise rejected after setTimeout(,1) should trigger unhandled rejection', function(done) { +asyncTest('Promise rejected after setTimeout(,1) should trigger' + + ' unhandled rejection', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -147,7 +152,8 @@ asyncTest('Promise rejected after setTimeout(,1) should trigger unhandled reject }); }); -asyncTest('Catching a promise rejection after setImmediate is not soon enough to stop unhandledRejection', function(done) { +asyncTest('Catching a promise rejection after setImmediate is not' + + ' soon enough to stop unhandledRejection', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -155,14 +161,15 @@ asyncTest('Catching a promise rejection after setImmediate is not soon enough to var _reject; var promise = new Promise(function(_, reject) { _reject = reject; - }) + }); _reject(e); setImmediate(function() { - promise.then(assert.fail, function(){}); + promise.then(assert.fail, function() {}); }); }); -asyncTest('When re-throwing new errors in a promise catch, only the re-thrown error should hit unhandledRejection', function(done) { +asyncTest('When re-throwing new errors in a promise catch, only the' + + ' re-thrown error should hit unhandledRejection', function(done) { var e = new Error(); var e2 = new Error(); onUnhandledSucceed(done, function(reason, promise) { @@ -175,7 +182,8 @@ asyncTest('When re-throwing new errors in a promise catch, only the re-thrown er }); }); -asyncTest('Test params of unhandledRejection for a synchronously-rejected promise', function(done) { +asyncTest('Test params of unhandledRejection for a synchronously-rejected' + + 'promise', function(done) { var e = new Error(); var e2 = new Error(); onUnhandledSucceed(done, function(reason, promise) { @@ -185,7 +193,9 @@ asyncTest('Test params of unhandledRejection for a synchronously-rejected promis var promise = Promise.reject(e); }); -asyncTest('When re-throwing new errors in a promise catch, only the re-thrown error should hit unhandledRejection: original promise rejected async with setTimeout(,1)', function(done) { +asyncTest('When re-throwing new errors in a promise catch, only the ' + + 're-thrown error should hit unhandledRejection: original promise' + + ' rejected async with setTimeout(,1)', function(done) { var e = new Error(); var e2 = new Error(); onUnhandledSucceed(done, function(reason, promise) { @@ -202,7 +212,9 @@ asyncTest('When re-throwing new errors in a promise catch, only the re-thrown er }); }); -asyncTest('When re-throwing new errors in a promise catch, only the re-thrown error should hit unhandledRejection: promise catch attached a process.nextTick after rejection', function(done) { +asyncTest('When re-throwing new errors in a promise catch, only the re-thrown' + + ' error should hit unhandledRejection: promise catch attached a' + + ' process.nextTick after rejection', function(done) { var e = new Error(); var e2 = new Error(); onUnhandledSucceed(done, function(reason, promise) { @@ -223,42 +235,50 @@ asyncTest('When re-throwing new errors in a promise catch, only the re-thrown er var promise2; }); -asyncTest('unhandledRejection should not be triggered if a promise catch is attached synchronously upon the promise\'s creation', function(done) { +asyncTest('unhandledRejection should not be triggered if a promise catch is' + + ' attached synchronously upon the promise\'s creation', + function(done) { var e = new Error(); onUnhandledFail(done); - Promise.reject(e).then(assert.fail, function(){}); + Promise.reject(e).then(assert.fail, function() {}); }); -asyncTest('unhandledRejection should not be triggered if a promise catch is attached synchronously upon the promise\'s creation', function(done) { +asyncTest('unhandledRejection should not be triggered if a promise catch is' + + ' attached synchronously upon the promise\'s creation', + function(done) { var e = new Error(); onUnhandledFail(done); new Promise(function(_, reject) { reject(e); - }).then(assert.fail, function(){}); + }).then(assert.fail, function() {}); }); -asyncTest('Attaching a promise catch in a process.nextTick is soon enough to prevent unhandledRejection', function(done) { +asyncTest('Attaching a promise catch in a process.nextTick is soon enough to' + + ' prevent unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); var promise = Promise.reject(e); process.nextTick(function() { - promise.then(assert.fail, function(){}); + promise.then(assert.fail, function() {}); }); }); -asyncTest('Attaching a promise catch in a process.nextTick is soon enough to prevent unhandledRejection', function(done) { +asyncTest('Attaching a promise catch in a process.nextTick is soon enough to' + + ' prevent unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); var promise = new Promise(function(_, reject) { reject(e); }); process.nextTick(function() { - promise.then(assert.fail, function(){}); + promise.then(assert.fail, function() {}); }); }); // State adapation tests -asyncTest('catching a promise which is asynchronously rejected (via resolution to an asynchronously-rejected promise) prevents unhandledRejection', function(done) { +asyncTest('catching a promise which is asynchronously rejected (via' + + 'resolution to an asynchronously-rejected promise) prevents' + + ' unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); Promise.resolve().then(function() { @@ -272,7 +292,8 @@ asyncTest('catching a promise which is asynchronously rejected (via resolution t }); }); -asyncTest('Catching a rejected promise derived from throwing in a fulfillment handler prevents unhandledRejection', function(done) { +asyncTest('Catching a rejected promise derived from throwing in a' + + ' fulfillment handler prevents unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); Promise.resolve().then(function() { @@ -282,7 +303,9 @@ asyncTest('Catching a rejected promise derived from throwing in a fulfillment ha }); }); -asyncTest('Catching a rejected promise derived from returning a synchronously-rejected promise in a fulfillment handler prevents unhandledRejection', function(done) { +asyncTest('Catching a rejected promise derived from returning a' + + ' synchronously-rejected promise in a fulfillment handler' + + ' prevents unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); Promise.resolve().then(function() { @@ -292,7 +315,9 @@ asyncTest('Catching a rejected promise derived from returning a synchronously-re }); }); -asyncTest('A rejected promise derived from returning an asynchronously-rejected promise in a fulfillment handler does trigger unhandledRejection', function(done) { +asyncTest('A rejected promise derived from returning an' + + ' asynchronously-rejected promise in a fulfillment handler' + + ' does trigger unhandledRejection', function(done) { var e = new Error(); var _promise; onUnhandledSucceed(done, function(reason, promise) { @@ -308,7 +333,8 @@ asyncTest('A rejected promise derived from returning an asynchronously-rejected }); }); -asyncTest('A rejected promise derived from throwing in a fulfillment handler does trigger unhandledRejection', function(done) { +asyncTest('A rejected promise derived from throwing in a fulfillment handler' + + ' does trigger unhandledRejection', function(done) { var e = new Error(); var _promise; onUnhandledSucceed(done, function(reason, promise) { @@ -320,7 +346,9 @@ asyncTest('A rejected promise derived from throwing in a fulfillment handler doe }); }); -asyncTest('A rejected promise derived from returning a synchronously-rejected promise in a fulfillment handler does trigger unhandledRejection', function(done) { +asyncTest('A rejected promise derived from returning a synchronously-rejected' + + ' promise in a fulfillment handler does trigger unhandledRejection', + function(done) { var e = new Error(); var _promise; onUnhandledSucceed(done, function(reason, promise) { @@ -333,13 +361,16 @@ asyncTest('A rejected promise derived from returning a synchronously-rejected pr }); // Combinations with Promise.all -asyncTest('Catching the Promise.all() of a collection that includes a rejected promise prevents unhandledRejection', function(done) { +asyncTest('Catching the Promise.all() of a collection that includes a' + + 'rejected promise prevents unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); Promise.all([Promise.reject(e)]).then(assert.fail, function() {}); }); -asyncTest('Catching the Promise.all() of a collection that includes a nextTick-async rejected promise prevents unhandledRejection', function(done) { +asyncTest('Catching the Promise.all() of a collection that includes a ' + + 'nextTick-async rejected promise prevents unhandledRejection', + function(done) { var e = new Error(); onUnhandledFail(done); var p = new Promise(function(_, reject) { @@ -353,7 +384,9 @@ asyncTest('Catching the Promise.all() of a collection that includes a nextTick-a }); }); -asyncTest('Failing to catch the Promise.all() of a collection that includes a rejected promise triggers unhandledRejection for the returned promise, not the passed promise', function(done) { +asyncTest('Failing to catch the Promise.all() of a collection that includes' + + ' a rejected promise triggers unhandledRejection for the returned' + + ' promise, not the passed promise', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -362,7 +395,8 @@ asyncTest('Failing to catch the Promise.all() of a collection that includes a re var p = Promise.all([Promise.reject(e)]); }); -asyncTest('Waiting setTimeout(, 10) to catch a promise causes an unhandledRejection + rejectionHandled pair', function(done) { +asyncTest('Waiting setTimeout(, 10) to catch a promise causes an' + + ' unhandledRejection + rejectionHandled pair', function(done) { clean(); var unhandledPromises = []; var e = new Error(); @@ -387,7 +421,9 @@ asyncTest('Waiting setTimeout(, 10) to catch a promise causes an unhandledReject }, 10); }); -asyncTest('Waiting for some combination of process.nextTick + promise microtasks to attach a catch handler is still soon enough to prevent unhandledRejection', function(done) { +asyncTest('Waiting for some combination of process.nextTick + promise' + + ' microtasks to attach a catch handler is still soon enough to' + + ' prevent unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); @@ -404,7 +440,9 @@ asyncTest('Waiting for some combination of process.nextTick + promise microtasks }); }); -asyncTest('Waiting for some combination of process.nextTick + promise microtasks to attach a catch handler is still soon enough to prevent unhandledRejection: inside setImmediate', function(done) { +asyncTest('Waiting for some combination of process.nextTick + promise' + + ' microtasks to attach a catch handler is still soon enough to ' + + 'prevent unhandledRejection: inside setImmediate', function(done) { var e = new Error(); onUnhandledFail(done); @@ -422,7 +460,9 @@ asyncTest('Waiting for some combination of process.nextTick + promise microtasks }); }); -asyncTest('Waiting for some combination of process.nextTick + promise microtasks to attach a catch handler is still soon enough to prevent unhandledRejection: inside setTimeout', function(done) { +asyncTest('Waiting for some combination of process.nextTick + promise ' + + 'microtasks to attach a catch handler is still soon enough to ' + + 'prevent unhandledRejection: inside setTimeout', function(done) { var e = new Error(); onUnhandledFail(done); @@ -440,7 +480,9 @@ asyncTest('Waiting for some combination of process.nextTick + promise microtasks }, 0); }); -asyncTest('Waiting for some combination of promise microtasks + process.nextTick to attach a catch handler is still soon enough to prevent unhandledRejection', function(done) { +asyncTest('Waiting for some combination of promise microtasks + ' + + 'process.nextTick to attach a catch handler is still soon enough' + + ' to prevent unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); @@ -457,7 +499,10 @@ asyncTest('Waiting for some combination of promise microtasks + process.nextTick }); }); -asyncTest('Waiting for some combination of promise microtasks + process.nextTick to attach a catch handler is still soon enough to prevent unhandledRejection: inside setImmediate', function(done) { +asyncTest('Waiting for some combination of promise microtasks +' + + ' process.nextTick to attach a catch handler is still soon enough' + + ' to prevent unhandledRejection: inside setImmediate', + function(done) { var e = new Error(); onUnhandledFail(done); @@ -475,7 +520,9 @@ asyncTest('Waiting for some combination of promise microtasks + process.nextTick }); }); -asyncTest('Waiting for some combination of promise microtasks + process.nextTick to attach a catch handler is still soon enough to prevent unhandledRejection: inside setTimeout', function(done) { +asyncTest('Waiting for some combination of promise microtasks +' + + ' process.nextTick to attach a catch handler is still soon enough' + + ' to prevent unhandledRejection: inside setTimeout', function(done) { var e = new Error(); onUnhandledFail(done); @@ -493,7 +540,9 @@ asyncTest('Waiting for some combination of promise microtasks + process.nextTick }, 0); }); -asyncTest('setImmediate + promise microtasks is too late to attach a catch handler; unhandledRejection will be triggered in that case. (setImmediate before promise creation/rejection)', function(done) { +asyncTest('setImmediate + promise microtasks is too late to attach a catch' + + ' handler; unhandledRejection will be triggered in that case.' + + ' (setImmediate before promise creation/rejection)', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -501,23 +550,25 @@ asyncTest('setImmediate + promise microtasks is too late to attach a catch handl }); var p = Promise.reject(e); setImmediate(function() { - Promise.resolve().then(function () { - p.catch(function(){}); + Promise.resolve().then(function() { + p.catch(function() {}); }); }); }); -asyncTest('setImmediate + promise microtasks is too late to attach a catch handler; unhandledRejection will be triggered in that case (setImmediate before promise creation/rejection)', function(done) { +asyncTest('setImmediate + promise microtasks is too late to attach a catch' + + ' handler; unhandledRejection will be triggered in that case' + + ' (setImmediate before promise creation/rejection)', function(done) { onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(undefined, reason); assert.strictEqual(p, promise); }); setImmediate(function() { - Promise.resolve().then(function () { - Promise.resolve().then(function () { - Promise.resolve().then(function () { - Promise.resolve().then(function () { - p.catch(function(){}); + Promise.resolve().then(function() { + Promise.resolve().then(function() { + Promise.resolve().then(function() { + Promise.resolve().then(function() { + p.catch(function() {}); }); }); }); @@ -526,18 +577,20 @@ asyncTest('setImmediate + promise microtasks is too late to attach a catch handl var p = Promise.reject(); }); -asyncTest('setImmediate + promise microtasks is too late to attach a catch handler; unhandledRejection will be triggered in that case (setImmediate after promise creation/rejection)', function(done) { +asyncTest('setImmediate + promise microtasks is too late to attach a catch' + + ' handler; unhandledRejection will be triggered in that case' + + ' (setImmediate after promise creation/rejection)', function(done) { onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(undefined, reason); assert.strictEqual(p, promise); }); var p = Promise.reject(); setImmediate(function() { - Promise.resolve().then(function () { - Promise.resolve().then(function () { - Promise.resolve().then(function () { - Promise.resolve().then(function () { - p.catch(function(){}); + Promise.resolve().then(function() { + Promise.resolve().then(function() { + Promise.resolve().then(function() { + Promise.resolve().then(function() { + p.catch(function() {}); }); }); }); @@ -545,7 +598,9 @@ asyncTest('setImmediate + promise microtasks is too late to attach a catch handl }); }); -asyncTest('Promise unhandledRejection handler does not interfere with domain error handlers being given exceptions thrown from nextTick.', function(done) { +asyncTest('Promise unhandledRejection handler does not interfere with domain' + + ' error handlers being given exceptions thrown from nextTick.', + function(done) { var d = domain.create(); var domainReceivedError; d.on('error', function(e) { @@ -566,7 +621,8 @@ asyncTest('Promise unhandledRejection handler does not interfere with domain err }); }); -asyncTest('nextTick is immediately scheduled when called inside an event handler', function(done) { +asyncTest('nextTick is immediately scheduled when called inside an event' + + ' handler', function(done) { clean(); var e = new Error('error'); process.on('unhandledRejection', function(reason, promise) { @@ -576,21 +632,23 @@ asyncTest('nextTick is immediately scheduled when called inside an event handler }); setTimeout(function() { order.push(2); - assert.deepEqual([1,2], order); + assert.deepEqual([1, 2], order); done(); }, 1); }); Promise.reject(e); }); -asyncTest('Throwing an error inside a rejectionHandled handler goes to unhandledException, and does not cause .catch() to throw an exception', function(done) { +asyncTest('Throwing an error inside a rejectionHandled handler goes to' + + ' unhandledException, and does not cause .catch() to throw an' + + 'exception', function(done) { clean(); var e = new Error(); var e2 = new Error(); var tearDownException = setupException(function(err) { - assert.equal(e2, err); - tearDownException(); - done(); + assert.equal(e2, err); + tearDownException(); + done(); }); process.on('rejectionHandled', function() { throw e2; @@ -598,7 +656,7 @@ asyncTest('Throwing an error inside a rejectionHandled handler goes to unhandled var p = Promise.reject(e); setTimeout(function() { try { - p.catch(function(){}); + p.catch(function() {}); } catch (e) { done(new Error('fail')); } diff --git a/test/parallel/test-punycode.js b/test/parallel/test-punycode.js index 4ac953849c0553..179bca51ec2fe0 100644 --- a/test/parallel/test-punycode.js +++ b/test/parallel/test-punycode.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var punycode = require('punycode'); var assert = require('assert'); diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index 17fa6df9247747..66497ac2d3b6db 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -240,7 +241,7 @@ assert.equal( // test overriding .unescape var prevUnescape = qs.unescape; -qs.unescape = function (str) { +qs.unescape = function(str) { return str.replace(/o/g, '_'); }; assert.deepEqual(qs.parse('foo=bor'), {f__: 'b_r'}); diff --git a/test/parallel/test-readdouble.js b/test/parallel/test-readdouble.js index 6dfc4015492783..c0dab8956593fe 100644 --- a/test/parallel/test-readdouble.js +++ b/test/parallel/test-readdouble.js @@ -1,3 +1,4 @@ +'use strict'; /* * Tests to verify we're reading in doubles correctly */ diff --git a/test/parallel/test-readfloat.js b/test/parallel/test-readfloat.js index 9b2fc612c73324..5572bbf18e291b 100644 --- a/test/parallel/test-readfloat.js +++ b/test/parallel/test-readfloat.js @@ -1,3 +1,4 @@ +'use strict'; /* * Tests to verify we're reading in floats correctly */ diff --git a/test/parallel/test-readint.js b/test/parallel/test-readint.js index 208907d03ee153..233128d792d068 100644 --- a/test/parallel/test-readint.js +++ b/test/parallel/test-readint.js @@ -1,3 +1,4 @@ +'use strict'; /* * Tests to verify we're reading in signed integers correctly */ diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index 69eb4bf51992cb..6ee9ad227896b1 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var readline = require('readline'); var EventEmitter = require('events').EventEmitter; @@ -98,7 +99,7 @@ function isWarned(emitter) { assert.equal(callCount, expectedLines.length - 1); rli.close(); - // sending multiple newlines at once that does not end with a new(empty) + // sending multiple newlines at once that does not end with a new(empty) // line and a `end` event fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); @@ -110,7 +111,7 @@ function isWarned(emitter) { }); rli.on('close', function() { callCount++; - }) + }); fi.emit('data', expectedLines.join('\n')); fi.emit('end'); assert.equal(callCount, expectedLines.length); @@ -191,31 +192,6 @@ function isWarned(emitter) { assert.equal(callCount, 1); rli.close(); - // keypress - [ - ['a'], - ['\x1b'], - ['\x1b[31m'], - ['\x1b[31m', '\x1b[39m'], - ['\x1b[31m', 'a', '\x1b[39m', 'a'] - ].forEach(function (keypresses) { - fi = new FakeInput(); - callCount = 0; - var remainingKeypresses = keypresses.slice(); - function keypressListener (ch, key) { - callCount++; - if (ch) assert(!key.code); - assert.equal(key.sequence, remainingKeypresses.shift()); - }; - readline.emitKeypressEvents(fi); - fi.on('keypress', keypressListener); - fi.emit('data', keypresses.join('')); - assert.equal(callCount, keypresses.length); - assert.equal(remainingKeypresses.length, 0); - fi.removeListener('keypress', keypressListener); - fi.emit('data', ''); // removes listener - }); - // calling readline without `new` fi = new FakeInput(); rli = readline.Interface({ input: fi, output: fi, terminal: terminal }); @@ -274,10 +250,14 @@ function isWarned(emitter) { assert.equal(readline.getStringWidth('A\ud83c\ude00BC'), 5); // surrogate // check if vt control chars are stripped - assert.equal(readline.stripVTControlCharacters('\u001b[31m> \u001b[39m'), '> '); - assert.equal(readline.stripVTControlCharacters('\u001b[31m> \u001b[39m> '), '> > '); - assert.equal(readline.stripVTControlCharacters('\u001b[31m\u001b[39m'), ''); - assert.equal(readline.stripVTControlCharacters('> '), '> '); + assert.equal(readline + .stripVTControlCharacters('\u001b[31m> \u001b[39m'), '> '); + assert.equal(readline + .stripVTControlCharacters('\u001b[31m> \u001b[39m> '), '> > '); + assert.equal(readline + .stripVTControlCharacters('\u001b[31m\u001b[39m'), ''); + assert.equal(readline + .stripVTControlCharacters('> '), '> '); assert.equal(readline.getStringWidth('\u001b[31m> \u001b[39m'), 2); assert.equal(readline.getStringWidth('\u001b[31m> \u001b[39m> '), 4); assert.equal(readline.getStringWidth('\u001b[31m\u001b[39m'), 0); @@ -286,7 +266,7 @@ function isWarned(emitter) { assert.deepEqual(fi.listeners(terminal ? 'keypress' : 'data'), []); // check EventEmitter memory leak - for (var i=0; i<12; i++) { + for (var i = 0; i < 12; i++) { var rl = readline.createInterface({ input: process.stdin, output: process.stdout @@ -309,7 +289,7 @@ function isWarned(emitter) { assert.ok(called); assert.doesNotThrow(function() { - rli.setPrompt("ddd> "); + rli.setPrompt('ddd> '); }); assert.doesNotThrow(function() { @@ -321,10 +301,10 @@ function isWarned(emitter) { }); assert.doesNotThrow(function() { - rli.question("What do you think of node.js? ", function(answer) { - console.log("Thank you for your valuable feedback:", answer); + rli.question('What do you think of node.js? ', function(answer) { + console.log('Thank you for your valuable feedback:', answer); rli.close(); - }) + }); }); }); diff --git a/test/parallel/test-readline-keys.js b/test/parallel/test-readline-keys.js new file mode 100644 index 00000000000000..150273f7993963 --- /dev/null +++ b/test/parallel/test-readline-keys.js @@ -0,0 +1,151 @@ +'use strict'; +var EventEmitter = require('events').EventEmitter; +var PassThrough = require('stream').PassThrough; +var assert = require('assert'); +var inherits = require('util').inherits; +var extend = require('util')._extend; +var Interface = require('readline').Interface; + + +function FakeInput() { + PassThrough.call(this); +} +inherits(FakeInput, PassThrough); + + +var fi = new FakeInput(); +var fo = new FakeInput(); +var rli = new Interface({ input: fi, output: fo, terminal: true }); + +var keys = []; +fi.on('keypress', function(s, k) { + keys.push(k); +}); + + +function addTest(sequences, expectedKeys) { + if (!Array.isArray(sequences)) { + sequences = [ sequences ]; + } + + if (!Array.isArray(expectedKeys)) { + expectedKeys = [ expectedKeys ]; + } + + expectedKeys = expectedKeys.map(function(k) { + return k ? extend({ ctrl: false, meta: false, shift: false }, k) : k; + }); + + keys = []; + + sequences.forEach(function(sequence) { + fi.write(sequence); + }); + assert.deepStrictEqual(keys, expectedKeys); +} + +// regular alphanumerics +addTest('io.JS', [ + { name: 'i', sequence: 'i' }, + { name: 'o', sequence: 'o' }, + undefined, // emitted as `emit('keypress', '.', undefined)` + { name: 'j', sequence: 'J', shift: true }, + { name: 's', sequence: 'S', shift: true }, +]); + +// named characters +addTest('\n\r\t', [ + { name: 'enter', sequence: '\n' }, + { name: 'return', sequence: '\r' }, + { name: 'tab', sequence: '\t' }, +]); + +// space and backspace +addTest('\b\x7f\x1b\b\x1b\x7f \x1b ', [ + { name: 'backspace', sequence: '\b' }, + { name: 'backspace', sequence: '\x7f' }, + { name: 'backspace', sequence: '\x1b\b', meta: true }, + { name: 'backspace', sequence: '\x1b\x7f', meta: true }, + { name: 'space', sequence: ' ' }, + { name: 'space', sequence: '\x1b ', meta: true }, +]); + +// control keys +addTest('\x01\x0b\x10', [ + { name: 'a', sequence: '\x01', ctrl: true }, + { name: 'k', sequence: '\x0b', ctrl: true }, + { name: 'p', sequence: '\x10', ctrl: true }, +]); + +// alt keys +addTest('a\x1baA\x1bA', [ + { name: 'a', sequence: 'a' }, + { name: 'a', sequence: '\x1ba', meta: true }, + { name: 'a', sequence: 'A', shift: true }, + { name: 'a', sequence: '\x1bA', meta: true, shift: true }, +]); + +// xterm/gnome +addTest('\x1bOA\x1bOB', [ + { name: 'up', sequence: '\x1bOA', code: 'OA' }, + { name: 'down', sequence: '\x1bOB', code: 'OB' }, +]); + +// old xterm shift-arrows +addTest('\x1bO2A\x1bO2B', [ + { name: 'up', sequence: '\x1bO2A', code: 'OA', shift: true }, + { name: 'down', sequence: '\x1bO2B', code: 'OB', shift: true }, +]); + +// gnome terminal +addTest('\x1b[A\x1b[B\x1b[2A\x1b[2B', [ + { name: 'up', sequence: '\x1b[A', code: '[A' }, + { name: 'down', sequence: '\x1b[B', code: '[B' }, + { name: 'up', sequence: '\x1b[2A', code: '[A', shift: true }, + { name: 'down', sequence: '\x1b[2B', code: '[B', shift: true }, +]); + +// rxvt +addTest('\x1b[20~\x1b[2$\x1b[2^', [ + { name: 'f9', sequence: '\x1b[20~', code: '[20~' }, + { name: 'insert', sequence: '\x1b[2$', code: '[2$', shift: true }, + { name: 'insert', sequence: '\x1b[2^', code: '[2^', ctrl: true }, +]); + +// xterm + modifiers +addTest('\x1b[20;5~\x1b[6;5^', [ + { name: 'f9', sequence: '\x1b[20;5~', code: '[20~', ctrl: true }, + { name: 'pagedown', sequence: '\x1b[6;5^', code: '[6^', ctrl: true }, +]); + +addTest('\x1b[H\x1b[5H\x1b[1;5H', [ + { name: 'home', sequence: '\x1b[H', code: '[H' }, + { name: 'home', sequence: '\x1b[5H', code: '[H', ctrl: true }, + { name: 'home', sequence: '\x1b[1;5H', code: '[H', ctrl: true }, +]); + +// escape sequences broken into multiple data chunks +addTest('\x1b[D\x1b[C\x1b[D\x1b[C'.split(''), [ + { name: 'left', sequence: '\x1b[D', code: '[D' }, + { name: 'right', sequence: '\x1b[C', code: '[C' }, + { name: 'left', sequence: '\x1b[D', code: '[D' }, + { name: 'right', sequence: '\x1b[C', code: '[C' }, +]); + +// escape sequences mixed with regular ones +addTest('\x1b[DD\x1b[2DD\x1b[2^D', [ + { name: 'left', sequence: '\x1b[D', code: '[D' }, + { name: 'd', sequence: 'D', shift: true }, + { name: 'left', sequence: '\x1b[2D', code: '[D', shift: true }, + { name: 'd', sequence: 'D', shift: true }, + { name: 'insert', sequence: '\x1b[2^', code: '[2^', ctrl: true }, + { name: 'd', sequence: 'D', shift: true }, +]); + +// color sequences +addTest('\x1b[31ma\x1b[39ma', [ + { name: 'undefined', sequence: '\x1b[31m', code: '[31m' }, + { name: 'a', sequence: 'a' }, + { name: 'undefined', sequence: '\x1b[39m', code: '[39m' }, + { name: 'a', sequence: 'a' }, +]); diff --git a/test/parallel/test-readline-set-raw-mode.js b/test/parallel/test-readline-set-raw-mode.js index 622d64181fbfe1..f9d5111581fa90 100644 --- a/test/parallel/test-readline-set-raw-mode.js +++ b/test/parallel/test-readline-set-raw-mode.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var readline = require('readline'); var Stream = require('stream'); diff --git a/test/parallel/test-readuint.js b/test/parallel/test-readuint.js index 293cb554ce343f..b984541bfe9eb0 100644 --- a/test/parallel/test-readuint.js +++ b/test/parallel/test-readuint.js @@ -1,3 +1,4 @@ +'use strict'; /* * A battery of tests to help us read a series of uints */ diff --git a/test/parallel/test-regress-GH-4256.js b/test/parallel/test-regress-GH-4256.js index ead32446b7b59b..f512e613162522 100644 --- a/test/parallel/test-regress-GH-4256.js +++ b/test/parallel/test-regress-GH-4256.js @@ -1,4 +1,5 @@ +'use strict'; process.domain = null; -timer = setTimeout(function() { - console.log("this console.log statement should not make node crash"); +var timer = setTimeout(function() { + console.log('this console.log statement should not make node crash'); }, 1); diff --git a/test/parallel/test-regress-GH-5927.js b/test/parallel/test-regress-GH-5927.js index dee33d854abd9c..541820c7a214c8 100644 --- a/test/parallel/test-regress-GH-5927.js +++ b/test/parallel/test-regress-GH-5927.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var readline = require('readline'); @@ -10,12 +11,12 @@ var origPause = rl.pause; rl.pause = function() { hasPaused = true; origPause.apply(this, arguments); -} +}; var origSetRawMode = rl._setRawMode; rl._setRawMode = function(mode) { assert.ok(hasPaused); origSetRawMode.apply(this, arguments); -} +}; rl.close(); diff --git a/test/parallel/test-regress-GH-6235.js b/test/parallel/test-regress-GH-6235.js index f929282b16ab75..2f2f17d9698fc9 100644 --- a/test/parallel/test-regress-GH-6235.js +++ b/test/parallel/test-regress-GH-6235.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-regress-GH-7511.js b/test/parallel/test-regress-GH-7511.js index aa7a10c0474149..0e5c4ded011a43 100644 --- a/test/parallel/test-regress-GH-7511.js +++ b/test/parallel/test-regress-GH-7511.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), vm = require('vm'); diff --git a/test/parallel/test-regress-GH-897.js b/test/parallel/test-regress-GH-897.js index fae1bd4b5d2a72..4b7ba61f9ceca9 100644 --- a/test/parallel/test-regress-GH-897.js +++ b/test/parallel/test-regress-GH-897.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-regress-GH-io-1068.js b/test/parallel/test-regress-GH-io-1068.js index e769e6b81a880d..cc91fe28df3d3e 100644 --- a/test/parallel/test-regress-GH-io-1068.js +++ b/test/parallel/test-regress-GH-io-1068.js @@ -1 +1,2 @@ +'use strict'; process.stdin.emit('end'); diff --git a/test/parallel/test-regress-GH-node-9326.js b/test/parallel/test-regress-GH-node-9326.js index 15a2abbdc55af0..5dc73e044e560b 100644 --- a/test/parallel/test-regress-GH-node-9326.js +++ b/test/parallel/test-regress-GH-node-9326.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var child_process = require('child_process'); diff --git a/test/parallel/test-regression-object-prototype.js b/test/parallel/test-regression-object-prototype.js index 17fe1727d37070..040e718948a581 100644 --- a/test/parallel/test-regression-object-prototype.js +++ b/test/parallel/test-regression-object-prototype.js @@ -1,3 +1,4 @@ +'use strict'; //console.log('puts before'); Object.prototype.xadsadsdasasdxx = function() { diff --git a/test/parallel/test-repl-.save.load.js b/test/parallel/test-repl-.save.load.js index d1c0f13e92f851..cf3224ecaf55a3 100644 --- a/test/parallel/test-repl-.save.load.js +++ b/test/parallel/test-repl-.save.load.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var util = require('util'); var join = require('path').join; @@ -13,7 +14,7 @@ function ArrayStream() { data.forEach(function(line) { self.emit('data', line + '\n'); }); - } + }; } util.inherits(ArrayStream, require('stream').Stream); ArrayStream.prototype.readable = true; @@ -28,7 +29,7 @@ var testMe = repl.start('', putIn); var testFile = [ - 'var top = function () {', + 'var top = function() {', 'var inner = {one:1};' ]; var saveFileName = join(common.tmpDir, 'test.save.js'); diff --git a/test/parallel/test-repl-autolibs.js b/test/parallel/test-repl-autolibs.js index c7727f574a6ca5..4103a19243aec5 100644 --- a/test/parallel/test-repl-autolibs.js +++ b/test/parallel/test-repl-autolibs.js @@ -1,30 +1,31 @@ +'use strict'; var assert = require('assert'); var util = require('util'); var repl = require('repl'); // A stream to push an array into a REPL function ArrayStream() { - this.run = function (data) { + this.run = function(data) { var self = this; - data.forEach(function (line) { + data.forEach(function(line) { self.emit('data', line + '\n'); }); - } + }; } util.inherits(ArrayStream, require('stream').Stream); ArrayStream.prototype.readable = true; ArrayStream.prototype.writable = true; -ArrayStream.prototype.resume = function () {}; -ArrayStream.prototype.write = function () {}; +ArrayStream.prototype.resume = function() {}; +ArrayStream.prototype.write = function() {}; -var putIn = new ArrayStream; +var putIn = new ArrayStream(); var testMe = repl.start('', putIn, null, true); test1(); -function test1(){ +function test1() { var gotWrite = false; - putIn.write = function (data) { + putIn.write = function(data) { gotWrite = true; if (data.length) { @@ -40,7 +41,7 @@ function test1(){ assert(gotWrite); } -function test2(){ +function test2() { var gotWrite = false; putIn.write = function(data) { gotWrite = true; diff --git a/test/parallel/test-repl-console.js b/test/parallel/test-repl-console.js index 45dad0f390d00d..e66fcb1621adc5 100644 --- a/test/parallel/test-repl-console.js +++ b/test/parallel/test-repl-console.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), Stream = require('stream'), @@ -5,7 +6,7 @@ var common = require('../common'), // create a dummy stream that does nothing var stream = new Stream(); -stream.write = stream.pause = stream.resume = function(){}; +stream.write = stream.pause = stream.resume = function() {}; stream.readable = stream.writable = true; var r = repl.start({ diff --git a/test/parallel/test-repl-domain.js b/test/parallel/test-repl-domain.js index 929cb0ffd1e80f..7528f502878f63 100644 --- a/test/parallel/test-repl-domain.js +++ b/test/parallel/test-repl-domain.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); @@ -11,7 +12,7 @@ function ArrayStream() { data.forEach(function(line) { self.emit('data', line + '\n'); }); - } + }; } util.inherits(ArrayStream, require('stream').Stream); ArrayStream.prototype.readable = true; @@ -26,15 +27,15 @@ putIn.write = function(data) { // Don't use assert for this because the domain might catch it, and // give a false negative. Don't throw, just print and exit. if (data === 'OK\n') { - console.log('ok'); + console.log('ok'); } else { - console.error(data); - process.exit(1); + console.error(data); + process.exit(1); } }; putIn.run([ - 'require("domain").create().on("error", function () { console.log("OK") })' - + '.run(function () { throw new Error("threw") })' + 'require("domain").create().on("error", function() { console.log("OK") })' + + '.run(function() { throw new Error("threw") })' ]); diff --git a/test/parallel/test-repl-end-emits-exit.js b/test/parallel/test-repl-end-emits-exit.js index bcb13a14afd021..e4bc4da78c142d 100644 --- a/test/parallel/test-repl-end-emits-exit.js +++ b/test/parallel/test-repl-end-emits-exit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), Stream = require('stream'), @@ -7,7 +8,7 @@ var common = require('../common'), // create a dummy stream that does nothing var stream = new Stream(); -stream.write = stream.pause = stream.resume = function(){}; +stream.write = stream.pause = stream.resume = function() {}; stream.readable = stream.writable = true; function testTerminalMode() { diff --git a/test/parallel/test-repl-harmony.js b/test/parallel/test-repl-harmony.js index 420b3163cce252..446aebe2d51c99 100644 --- a/test/parallel/test-repl-harmony.js +++ b/test/parallel/test-repl-harmony.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-repl-options.js b/test/parallel/test-repl-options.js index e58f459393ecba..0c5f997350265f 100644 --- a/test/parallel/test-repl-options.js +++ b/test/parallel/test-repl-options.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), Stream = require('stream'), @@ -7,7 +8,7 @@ common.globalCheck = false; // create a dummy stream that does nothing var stream = new Stream(); -stream.write = stream.pause = stream.resume = function(){}; +stream.write = stream.pause = stream.resume = function() {}; stream.readable = stream.writable = true; // 1, mostly defaults @@ -64,3 +65,17 @@ assert.equal(r2.rli.input, r2.inputStream); assert.equal(r2.rli.output, r2.outputStream); assert.equal(r2.rli.terminal, false); +<<<<<<< HEAD +======= +// testing out "magic" replMode +var r3 = repl.start({ + input: stream, + output: stream, + writer: writer, + replMode: repl.REPL_MODE_MAGIC, + historySize: 50 +}); + +assert.equal(r3.replMode, repl.REPL_MODE_MAGIC); +assert.equal(r3.historySize, 50); +>>>>>>> f29762f... test: enable linting for tests diff --git a/test/parallel/test-repl-require-cache.js b/test/parallel/test-repl-require-cache.js index 3ab3b7062c2603..d9b4d71d484640 100644 --- a/test/parallel/test-repl-require-cache.js +++ b/test/parallel/test-repl-require-cache.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), repl = require('repl'); diff --git a/test/parallel/test-repl-reset-event.js b/test/parallel/test-repl-reset-event.js index eee31e24bee5a0..e6157956d43a65 100644 --- a/test/parallel/test-repl-reset-event.js +++ b/test/parallel/test-repl-reset-event.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); common.globalCheck = false; @@ -7,7 +8,7 @@ var Stream = require('stream'); // create a dummy stream that does nothing var dummy = new Stream(); -dummy.write = dummy.pause = dummy.resume = function(){}; +dummy.write = dummy.pause = dummy.resume = function() {}; dummy.readable = dummy.writable = true; function testReset(cb) { @@ -20,7 +21,8 @@ function testReset(cb) { r.on('reset', function(context) { assert(!!context, 'REPL did not emit a context with reset event'); assert.equal(context, r.context, 'REPL emitted incorrect context'); - assert.equal(context.foo, undefined, 'REPL emitted the previous context, and is not using global as context'); + assert.equal(context.foo, undefined, 'REPL emitted the previous context' + + ', and is not using global as context'); context.foo = 42; cb(); }); @@ -35,7 +37,8 @@ function testResetGlobal(cb) { }); r.context.foo = 42; r.on('reset', function(context) { - assert.equal(context.foo, 42, '"foo" property is missing from REPL using global as context'); + assert.equal(context.foo, 42, + '"foo" property is missing from REPL using global as context'); cb(); }); r.resetContext(); diff --git a/test/parallel/test-repl-setprompt.js b/test/parallel/test-repl-setprompt.js index 56de10023f831f..b89dd6c928ab0a 100644 --- a/test/parallel/test-repl-setprompt.js +++ b/test/parallel/test-repl-setprompt.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), spawn = require('child_process').spawn, @@ -9,14 +10,14 @@ var args = [ 'var e = new (require("repl")).REPLServer("foo.. "); e.context.e = e;', ]; -var p = "bar.. "; +var p = 'bar.. '; var child = spawn(process.execPath, args); child.stdout.setEncoding('utf8'); var data = ''; -child.stdout.on('data', function(d) { data += d }); +child.stdout.on('data', function(d) { data += d; }); child.stdin.end(util.format("e.setPrompt('%s');%s", p, os.EOL)); diff --git a/test/parallel/test-repl-syntax-error-handling.js b/test/parallel/test-repl-syntax-error-handling.js index 79489628b588c7..66e8fb6b352c56 100644 --- a/test/parallel/test-repl-syntax-error-handling.js +++ b/test/parallel/test-repl-syntax-error-handling.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-repl-tab-complete.js b/test/parallel/test-repl-tab-complete.js index c6a07f4017bef4..659c8046a98173 100644 --- a/test/parallel/test-repl-tab-complete.js +++ b/test/parallel/test-repl-tab-complete.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -11,7 +12,7 @@ function ArrayStream() { data.forEach(function(line) { self.emit('data', line + '\n'); }); - } + }; } util.inherits(ArrayStream, require('stream').Stream); ArrayStream.prototype.readable = true; @@ -48,7 +49,7 @@ putIn.run(['.clear']); // Tab Complete will not break in an ternary operator with () putIn.run([ - 'var inner = ( true ' , + 'var inner = ( true ', '?', '{one: 1} : ' ]); @@ -60,7 +61,7 @@ putIn.run(['.clear']); // Tab Complete will return a simple local variable putIn.run([ - 'var top = function () {', + 'var top = function() {', 'var inner = {one:1};' ]); testMe.complete('inner.o', function(error, data) { @@ -78,7 +79,7 @@ putIn.run(['.clear']); // Tab Complete will return a complex local variable putIn.run([ - 'var top = function () {', + 'var top = function() {', 'var inner = {', ' one:1', '};' @@ -92,7 +93,7 @@ putIn.run(['.clear']); // Tab Complete will return a complex local variable even if the function // has parameters putIn.run([ - 'var top = function (one, two) {', + 'var top = function(one, two) {', 'var inner = {', ' one:1', '};' @@ -106,7 +107,7 @@ putIn.run(['.clear']); // Tab Complete will return a complex local variable even if the // scope is nested inside an immediately executed function putIn.run([ - 'var top = function () {', + 'var top = function() {', '(function test () {', 'var inner = {', ' one:1', @@ -121,7 +122,7 @@ putIn.run(['.clear']); // currently does not work, but should not break note the inner function // def has the params and { on a separate line putIn.run([ - 'var top = function () {', + 'var top = function() {', 'r = function test (', ' one, two) {', 'var inner = {', @@ -136,7 +137,7 @@ putIn.run(['.clear']); // currently does not work, but should not break, not the { putIn.run([ - 'var top = function () {', + 'var top = function() {', 'r = function test ()', '{', 'var inner = {', @@ -151,7 +152,7 @@ putIn.run(['.clear']); // currently does not work, but should not break putIn.run([ - 'var top = function () {', + 'var top = function() {', 'r = function test (', ')', '{', @@ -181,7 +182,7 @@ var spaceTimeout = setTimeout(function() { }, 1000); testMe.complete(' ', function(error, data) { - assert.deepEqual(data, [[],undefined]); + assert.deepEqual(data, [[], undefined]); clearTimeout(spaceTimeout); }); diff --git a/test/parallel/test-repl-timeout-throw.js b/test/parallel/test-repl-timeout-throw.js index eea2bea3ac9389..6c540c9e3197de 100644 --- a/test/parallel/test-repl-timeout-throw.js +++ b/test/parallel/test-repl-timeout-throw.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); @@ -14,10 +15,12 @@ child.stdout.on('data', function(c) { stdout += c; }); -child.stdin.write = function(original) { return function(c) { - process.stderr.write(c); - return original.call(child.stdin, c); -}}(child.stdin.write); +child.stdin.write = function(original) { + return function(c) { + process.stderr.write(c); + return original.call(child.stdin, c); + }; +}(child.stdin.write); child.stdout.once('data', function() { child.stdin.write('var throws = 0;'); diff --git a/test/parallel/test-repl.js b/test/parallel/test-repl.js index e1087a2e1daf8e..1bcc13e4d23ba8 100644 --- a/test/parallel/test-repl.js +++ b/test/parallel/test-repl.js @@ -1,3 +1,4 @@ +/* eslint-disable max-len, strict */ var common = require('../common'); var assert = require('assert'); @@ -172,7 +173,7 @@ function error_test() { { client: client_unix, send: '1 }', expect: '{ a: 1 }' }, // Multiline anonymous function with comment - { client: client_unix, send: '(function () {', + { client: client_unix, send: '(function() {', expect: prompt_multiline }, { client: client_unix, send: '// blah', expect: prompt_multiline }, @@ -183,7 +184,7 @@ function error_test() { // npm prompt error message { client: client_unix, send: 'npm install foobar', expect: expect_npm }, - { client: client_unix, send: '(function () {\n\nreturn 1;\n})()', + { client: client_unix, send: '(function() {\n\nreturn 1;\n})()', expect: '1' }, { client: client_unix, send: '{\n\na: 1\n}', expect: '{ a: 1 }' }, diff --git a/test/parallel/test-require-cache.js b/test/parallel/test-require-cache.js index a069d0a799892a..f2245345e3e4bd 100644 --- a/test/parallel/test-require-cache.js +++ b/test/parallel/test-require-cache.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-require-dot.js b/test/parallel/test-require-dot.js index 2551d88d2204e8..aab466e3eb6204 100644 --- a/test/parallel/test-require-dot.js +++ b/test/parallel/test-require-dot.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var module = require('module'); diff --git a/test/parallel/test-require-exceptions.js b/test/parallel/test-require-exceptions.js index 16c63a90aa41ed..e7a191b47ad6f2 100644 --- a/test/parallel/test-require-exceptions.js +++ b/test/parallel/test-require-exceptions.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-require-extensions-main.js b/test/parallel/test-require-extensions-main.js index 06d28ab30bddcf..6e67d3ae045bb6 100644 --- a/test/parallel/test-require-extensions-main.js +++ b/test/parallel/test-require-extensions-main.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js b/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js index cc2cd94ea6994c..1837a17bab0add 100644 --- a/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js +++ b/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js @@ -1,3 +1,5 @@ +/* eslint-disable max-len */ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-require-extensions-same-filename-as-dir.js b/test/parallel/test-require-extensions-same-filename-as-dir.js index 387620afa74cb2..41051dad45e10f 100644 --- a/test/parallel/test-require-extensions-same-filename-as-dir.js +++ b/test/parallel/test-require-extensions-same-filename-as-dir.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-require-json.js b/test/parallel/test-require-json.js index dbf8c8f866d8c6..4c17fc8d025d73 100644 --- a/test/parallel/test-require-json.js +++ b/test/parallel/test-require-json.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); try { diff --git a/test/parallel/test-require-process.js b/test/parallel/test-require-process.js index 4693b4984e6dfe..fdd921a61195e5 100644 --- a/test/parallel/test-require-process.js +++ b/test/parallel/test-require-process.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var nativeProcess = require('process'); diff --git a/test/parallel/test-require-resolve.js b/test/parallel/test-require-resolve.js index c11ff65ac43307..13897c74da1752 100644 --- a/test/parallel/test-require-resolve.js +++ b/test/parallel/test-require-resolve.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var fixturesDir = common.fixturesDir; var assert = require('assert'); diff --git a/test/parallel/test-signal-handler.js b/test/parallel/test-signal-handler.js index 30cad31eef5995..f186287b0c72a7 100644 --- a/test/parallel/test-signal-handler.js +++ b/test/parallel/test-signal-handler.js @@ -1,3 +1,4 @@ +'use strict'; // SIGUSR1 and SIGHUP are not supported on Windows if (process.platform === 'win32') { process.exit(0); @@ -39,7 +40,7 @@ setInterval(function() { // has been previously registered, and `process.listeners(SIGNAL).length === 1` process.on('SIGHUP', function() {}); process.removeAllListeners('SIGHUP'); -process.on('SIGHUP', function() { sighup = true }); +process.on('SIGHUP', function() { sighup = true; }); process.kill(process.pid, 'SIGHUP'); process.on('exit', function() { diff --git a/test/parallel/test-signal-safety.js b/test/parallel/test-signal-safety.js index b037232a6b89f7..549c26662f717a 100644 --- a/test/parallel/test-signal-safety.js +++ b/test/parallel/test-signal-safety.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Signal = process.binding('signal_wrap').Signal; diff --git a/test/parallel/test-signal-unregister.js b/test/parallel/test-signal-unregister.js index c3ab108dffbf08..b65ade73db9422 100644 --- a/test/parallel/test-signal-unregister.js +++ b/test/parallel/test-signal-unregister.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-smalloc.js b/test/parallel/test-smalloc.js index ef1aa60bad6838..ce4e4f43cd08f0 100644 --- a/test/parallel/test-smalloc.js +++ b/test/parallel/test-smalloc.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var os = require('os'); diff --git a/test/parallel/test-stdin-hang.js b/test/parallel/test-stdin-hang.js index c22a097925b456..4818a9ee952026 100644 --- a/test/parallel/test-stdin-hang.js +++ b/test/parallel/test-stdin-hang.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); // This test *only* verifies that invoking the stdin getter does not diff --git a/test/parallel/test-stdin-pause-resume-sync.js b/test/parallel/test-stdin-pause-resume-sync.js index fdb8e030b70edb..4fe4d445a2443e 100644 --- a/test/parallel/test-stdin-pause-resume-sync.js +++ b/test/parallel/test-stdin-pause-resume-sync.js @@ -1,3 +1,4 @@ +'use strict'; console.error('before opening stdin'); process.stdin.resume(); console.error('stdin opened'); diff --git a/test/parallel/test-stdin-pause-resume.js b/test/parallel/test-stdin-pause-resume.js index a9282d5aa030ed..2685deb0e9b33c 100644 --- a/test/parallel/test-stdin-pause-resume.js +++ b/test/parallel/test-stdin-pause-resume.js @@ -1,3 +1,4 @@ +'use strict'; console.error('before opening stdin'); process.stdin.resume(); console.error('stdin opened'); diff --git a/test/parallel/test-stdin-resume-pause.js b/test/parallel/test-stdin-resume-pause.js index 6290ff7999b250..963fd989f085a3 100644 --- a/test/parallel/test-stdin-resume-pause.js +++ b/test/parallel/test-stdin-resume-pause.js @@ -1,2 +1,3 @@ +'use strict'; process.stdin.resume(); process.stdin.pause(); diff --git a/test/parallel/test-stdio-closed.js b/test/parallel/test-stdio-closed.js index 2543d8b021b91d..2101f85ac061c3 100644 --- a/test/parallel/test-stdio-closed.js +++ b/test/parallel/test-stdio-closed.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-stdio-readable-writable.js b/test/parallel/test-stdio-readable-writable.js index 95ae679bca0389..f8a8923498cb03 100644 --- a/test/parallel/test-stdio-readable-writable.js +++ b/test/parallel/test-stdio-readable-writable.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stdout-close-unref.js b/test/parallel/test-stdout-close-unref.js index 0b03e7142a8615..12a031562bf6f0 100644 --- a/test/parallel/test-stdout-close-unref.js +++ b/test/parallel/test-stdout-close-unref.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-stream-big-packet.js b/test/parallel/test-stream-big-packet.js index cfde7e47fb700a..a9f6064c7e7277 100644 --- a/test/parallel/test-stream-big-packet.js +++ b/test/parallel/test-stream-big-packet.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -5,20 +6,20 @@ var stream = require('stream'); var passed = false; -function PassThrough () { +function PassThrough() { stream.Transform.call(this); }; util.inherits(PassThrough, stream.Transform); -PassThrough.prototype._transform = function (chunk, encoding, done) { +PassThrough.prototype._transform = function(chunk, encoding, done) { this.push(chunk); done(); }; -function TestStream () { +function TestStream() { stream.Transform.call(this); }; util.inherits(TestStream, stream.Transform); -TestStream.prototype._transform = function (chunk, encoding, done) { +TestStream.prototype._transform = function(chunk, encoding, done) { if (!passed) { // Char 'a' only exists in the last write passed = chunk.toString().indexOf('a') >= 0; @@ -47,6 +48,6 @@ assert(s2.write('tiny')); setImmediate(s1.write.bind(s1), 'later'); // Assert after two IO loops when all operations have been done. -process.on('exit', function () { +process.on('exit', function() { assert(passed, 'Large buffer is not handled properly by Writable Stream'); }); diff --git a/test/parallel/test-stream-big-push.js b/test/parallel/test-stream-big-push.js index b4ed8f8a527acd..e02ff98d3c7454 100644 --- a/test/parallel/test-stream-big-push.js +++ b/test/parallel/test-stream-big-push.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var stream = require('stream'); diff --git a/test/parallel/test-stream-duplex.js b/test/parallel/test-stream-duplex.js index 8efc9d4b5f4160..0e8789d6bf5555 100644 --- a/test/parallel/test-stream-duplex.js +++ b/test/parallel/test-stream-duplex.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -11,21 +12,21 @@ assert(stream._writableState.objectMode); var written; var read; -stream._write = function (obj, _, cb) { +stream._write = function(obj, _, cb) { written = obj; cb(); }; -stream._read = function () {}; +stream._read = function() {}; -stream.on('data', function (obj) { +stream.on('data', function(obj) { read = obj; }); stream.push({ val: 1 }); stream.end({ val: 2 }); -process.on('exit', function () { +process.on('exit', function() { assert(read.val === 1); assert(written.val === 2); }); diff --git a/test/parallel/test-stream-end-paused.js b/test/parallel/test-stream-end-paused.js index 72825dc440df91..585d6c327fd592 100644 --- a/test/parallel/test-stream-end-paused.js +++ b/test/parallel/test-stream-end-paused.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var gotEnd = false; diff --git a/test/parallel/test-stream-ispaused.js b/test/parallel/test-stream-ispaused.js index fe895ce7c39884..8112dc733a7205 100644 --- a/test/parallel/test-stream-ispaused.js +++ b/test/parallel/test-stream-ispaused.js @@ -1,9 +1,10 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var stream = require('stream'); -var readable = new stream.Readable; +var readable = new stream.Readable(); // _read is a noop, here. readable._read = Function(); diff --git a/test/parallel/test-stream-pipe-after-end.js b/test/parallel/test-stream-pipe-after-end.js index a2fece3f7f6264..4bead73f68ce5b 100644 --- a/test/parallel/test-stream-pipe-after-end.js +++ b/test/parallel/test-stream-pipe-after-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-pipe-cleanup.js b/test/parallel/test-stream-pipe-cleanup.js index b2963c4f56c1a3..08da96f92c3a0f 100644 --- a/test/parallel/test-stream-pipe-cleanup.js +++ b/test/parallel/test-stream-pipe-cleanup.js @@ -1,3 +1,4 @@ +'use strict'; // This test asserts that Stream.prototype.pipe does not leave listeners // hanging on the source or dest. diff --git a/test/parallel/test-stream-pipe-error-handling.js b/test/parallel/test-stream-pipe-error-handling.js index 18ce5a1edef021..031a0da7e395db 100644 --- a/test/parallel/test-stream-pipe-error-handling.js +++ b/test/parallel/test-stream-pipe-error-handling.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Stream = require('stream').Stream; @@ -41,8 +42,8 @@ var Stream = require('stream').Stream; var R = Stream.Readable; var W = Stream.Writable; - var r = new R; - var w = new W; + var r = new R(); + var w = new W(); var removed = false; var didTest = false; @@ -76,8 +77,8 @@ var Stream = require('stream').Stream; var R = Stream.Readable; var W = Stream.Writable; - var r = new R; - var w = new W; + var r = new R(); + var w = new W(); var removed = false; var didTest = false; var caught = false; diff --git a/test/parallel/test-stream-pipe-event.js b/test/parallel/test-stream-pipe-event.js index bcae20c581ebbd..0d10533b0c496a 100644 --- a/test/parallel/test-stream-pipe-event.js +++ b/test/parallel/test-stream-pipe-event.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var stream = require('stream'); var assert = require('assert'); diff --git a/test/parallel/test-stream-push-order.js b/test/parallel/test-stream-push-order.js index 5e403c7824beaf..d67233aff7a498 100644 --- a/test/parallel/test-stream-push-order.js +++ b/test/parallel/test-stream-push-order.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var Readable = require('stream').Readable; var assert = require('assert'); @@ -9,7 +10,7 @@ var s = new Readable({ var list = ['1', '2', '3', '4', '5', '6']; -s._read = function (n) { +s._read = function(n) { var one = list.shift(); if (!one) { s.push(null); @@ -24,8 +25,8 @@ var v = s.read(0); // ACTUALLY [1, 3, 5, 6, 4, 2] -process.on("exit", function () { +process.on('exit', function() { assert.deepEqual(s._readableState.buffer, ['1', '2', '3', '4', '5', '6']); - console.log("ok"); + console.log('ok'); }); diff --git a/test/parallel/test-stream-push-strings.js b/test/parallel/test-stream-push-strings.js index f673173de5ea57..0d9c0653c0dc66 100644 --- a/test/parallel/test-stream-push-strings.js +++ b/test/parallel/test-stream-push-strings.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-readable-constructor-set-methods.js b/test/parallel/test-stream-readable-constructor-set-methods.js index a88ffcd67a1446..928ce31a8ebe7b 100644 --- a/test/parallel/test-stream-readable-constructor-set-methods.js +++ b/test/parallel/test-stream-readable-constructor-set-methods.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -12,7 +13,7 @@ function _read(n) { var r = new Readable({ read: _read }); r.resume(); -process.on('exit', function () { +process.on('exit', function() { assert.equal(r._read, _read); assert(_readCalled); }); diff --git a/test/parallel/test-stream-readable-event.js b/test/parallel/test-stream-readable-event.js index 2d7d1cc4f9020e..965fc82c05a1d9 100644 --- a/test/parallel/test-stream-readable-event.js +++ b/test/parallel/test-stream-readable-event.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-readable-flow-recursion.js b/test/parallel/test-stream-readable-flow-recursion.js index c3dfbef53bd971..07edd579f1deea 100644 --- a/test/parallel/test-stream-readable-flow-recursion.js +++ b/test/parallel/test-stream-readable-flow-recursion.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-transform-constructor-set-methods.js b/test/parallel/test-stream-transform-constructor-set-methods.js index 55e64ed9b2e733..c24c273b6f20e1 100644 --- a/test/parallel/test-stream-transform-constructor-set-methods.js +++ b/test/parallel/test-stream-transform-constructor-set-methods.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -23,7 +24,7 @@ var t = new Transform({ t.end(new Buffer('blerg')); t.resume(); -process.on('exit', function () { +process.on('exit', function() { assert.equal(t._transform, _transform); assert.equal(t._flush, _flush); assert(_transformCalled); diff --git a/test/parallel/test-stream-transform-objectmode-falsey-value.js b/test/parallel/test-stream-transform-objectmode-falsey-value.js index 89feabef118e59..762f0500ad3e60 100644 --- a/test/parallel/test-stream-transform-objectmode-falsey-value.js +++ b/test/parallel/test-stream-transform-objectmode-falsey-value.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-transform-split-objectmode.js b/test/parallel/test-stream-transform-split-objectmode.js index df10ed1b6553e7..24833ece051e9e 100644 --- a/test/parallel/test-stream-transform-split-objectmode.js +++ b/test/parallel/test-stream-transform-split-objectmode.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -10,19 +11,19 @@ assert(!parser._writableState.objectMode); assert(parser._readableState.highWaterMark === 16); assert(parser._writableState.highWaterMark === (16 * 1024)); -parser._transform = function (chunk, enc, callback) { +parser._transform = function(chunk, enc, callback) { callback(null, { val : chunk[0] }); }; var parsed; -parser.on('data', function (obj) { +parser.on('data', function(obj) { parsed = obj; }); parser.end(new Buffer([42])); -process.on('exit', function () { +process.on('exit', function() { assert(parsed.val === 42); }); @@ -34,18 +35,18 @@ assert(serializer._writableState.objectMode); assert(serializer._readableState.highWaterMark === (16 * 1024)); assert(serializer._writableState.highWaterMark === 16); -serializer._transform = function (obj, _, callback) { +serializer._transform = function(obj, _, callback) { callback(null, new Buffer([obj.val])); }; var serialized; -serializer.on('data', function (chunk) { +serializer.on('data', function(chunk) { serialized = chunk; }); serializer.write({ val : 42 }); -process.on('exit', function () { +process.on('exit', function() { assert(serialized[0] === 42); }); diff --git a/test/parallel/test-stream-unshift-empty-chunk.js b/test/parallel/test-stream-unshift-empty-chunk.js index c985d4bc37d279..e6c427221294a2 100644 --- a/test/parallel/test-stream-unshift-empty-chunk.js +++ b/test/parallel/test-stream-unshift-empty-chunk.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-unshift-read-race.js b/test/parallel/test-stream-unshift-read-race.js index dd7c6dfb37e10c..90f519b5b5d738 100644 --- a/test/parallel/test-stream-unshift-read-race.js +++ b/test/parallel/test-stream-unshift-read-race.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-writable-change-default-encoding.js b/test/parallel/test-stream-writable-change-default-encoding.js index 3e2277ad980c3d..a6fcda3e62a517 100644 --- a/test/parallel/test-stream-writable-change-default-encoding.js +++ b/test/parallel/test-stream-writable-change-default-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -11,7 +12,7 @@ function MyWritable(fn, options) { util.inherits(MyWritable, stream.Writable); -MyWritable.prototype._write = function (chunk, encoding, callback) { +MyWritable.prototype._write = function(chunk, encoding, callback) { this.fn(Buffer.isBuffer(chunk), typeof chunk, encoding); callback(); }; diff --git a/test/parallel/test-stream-writable-constructor-set-methods.js b/test/parallel/test-stream-writable-constructor-set-methods.js index 496ce6697582d0..47fc458ce9713b 100644 --- a/test/parallel/test-stream-writable-constructor-set-methods.js +++ b/test/parallel/test-stream-writable-constructor-set-methods.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -25,7 +26,7 @@ w2.write(new Buffer('blerg')); w2.write(new Buffer('blerg')); w2.end(); -process.on('exit', function () { +process.on('exit', function() { assert.equal(w._write, _write); assert(_writeCalled); assert.equal(w2._writev, _writev); diff --git a/test/parallel/test-stream-writable-decoded-encoding.js b/test/parallel/test-stream-writable-decoded-encoding.js index fb530d0830a5d9..b637838c0c65be 100644 --- a/test/parallel/test-stream-writable-decoded-encoding.js +++ b/test/parallel/test-stream-writable-decoded-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -11,7 +12,7 @@ function MyWritable(fn, options) { util.inherits(MyWritable, stream.Writable); -MyWritable.prototype._write = function (chunk, encoding, callback) { +MyWritable.prototype._write = function(chunk, encoding, callback) { this.fn(Buffer.isBuffer(chunk), typeof chunk, encoding); callback(); }; diff --git a/test/parallel/test-stream-writev.js b/test/parallel/test-stream-writev.js index 2a2ed3cdae3c07..f73270f2ff53ba 100644 --- a/test/parallel/test-stream-writev.js +++ b/test/parallel/test-stream-writev.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -45,19 +46,24 @@ function test(decode, uncork, multi, next) { }; var expectChunks = decode ? - [{ encoding: 'buffer', - chunk: [104, 101, 108, 108, 111, 44, 32] }, - { encoding: 'buffer', chunk: [119, 111, 114, 108, 100] }, - { encoding: 'buffer', chunk: [33] }, - { encoding: 'buffer', - chunk: [10, 97, 110, 100, 32, 116, 104, 101, 110, 46, 46, 46] }, - { encoding: 'buffer', - chunk: [250, 206, 190, 167, 222, 173, 190, 239, 222, 202, 251, 173] }] : - [{ encoding: 'ascii', chunk: 'hello, ' }, + [ + { encoding: 'buffer', + chunk: [104, 101, 108, 108, 111, 44, 32] }, + { encoding: 'buffer', + chunk: [119, 111, 114, 108, 100] }, + { encoding: 'buffer', + chunk: [33] }, + { encoding: 'buffer', + chunk: [10, 97, 110, 100, 32, 116, 104, 101, 110, 46, 46, 46] }, + { encoding: 'buffer', + chunk: [250, 206, 190, 167, 222, 173, 190, 239, 222, 202, 251, 173]} + ] : [ + { encoding: 'ascii', chunk: 'hello, ' }, { encoding: 'utf8', chunk: 'world' }, { encoding: 'buffer', chunk: [33] }, { encoding: 'binary', chunk: '\nand then...' }, - { encoding: 'hex', chunk: 'facebea7deadbeefdecafbad' }]; + { encoding: 'hex', chunk: 'facebea7deadbeefdecafbad' } + ]; var actualChunks; w._writev = function(chunks, cb) { diff --git a/test/parallel/test-stream2-base64-single-char-read-end.js b/test/parallel/test-stream2-base64-single-char-read-end.js index 2082c714cc69a5..37a97cd817e05b 100644 --- a/test/parallel/test-stream2-base64-single-char-read-end.js +++ b/test/parallel/test-stream2-base64-single-char-read-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var R = require('_stream_readable'); var W = require('_stream_writable'); @@ -27,7 +28,7 @@ dst._write = function(chunk, enc, cb) { src.on('end', function() { assert.equal(Buffer.concat(accum) + '', 'MQ=='); clearTimeout(timeout); -}) +}); src.pipe(dst); diff --git a/test/parallel/test-stream2-compatibility.js b/test/parallel/test-stream2-compatibility.js index 72b1e428505988..9eab7b713bf167 100644 --- a/test/parallel/test-stream2-compatibility.js +++ b/test/parallel/test-stream2-compatibility.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var R = require('_stream_readable'); var assert = require('assert'); diff --git a/test/parallel/test-stream2-finish-pipe.js b/test/parallel/test-stream2-finish-pipe.js index beabea0f0e5728..913bb7b0b4db09 100644 --- a/test/parallel/test-stream2-finish-pipe.js +++ b/test/parallel/test-stream2-finish-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var stream = require('stream'); var Buffer = require('buffer').Buffer; diff --git a/test/parallel/test-stream2-large-read-stall.js b/test/parallel/test-stream2-large-read-stall.js index 55d25a9b7366df..4cd89599fee730 100644 --- a/test/parallel/test-stream2-large-read-stall.js +++ b/test/parallel/test-stream2-large-read-stall.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream2-objects.js b/test/parallel/test-stream2-objects.js index d7c532917962da..a2f554a0b8a004 100644 --- a/test/parallel/test-stream2-objects.js +++ b/test/parallel/test-stream2-objects.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var Readable = require('_stream_readable'); var Writable = require('_stream_writable'); diff --git a/test/parallel/test-stream2-pipe-error-handling.js b/test/parallel/test-stream2-pipe-error-handling.js index c7303accead89b..9eddbdd90d00c3 100644 --- a/test/parallel/test-stream2-pipe-error-handling.js +++ b/test/parallel/test-stream2-pipe-error-handling.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var stream = require('stream'); diff --git a/test/parallel/test-stream2-pipe-error-once-listener.js b/test/parallel/test-stream2-pipe-error-once-listener.js index 0dbe8782e92229..f2ecb87ce97a75 100644 --- a/test/parallel/test-stream2-pipe-error-once-listener.js +++ b/test/parallel/test-stream2-pipe-error-once-listener.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream2-push.js b/test/parallel/test-stream2-push.js index 9268f052a2381a..b58bce143585f4 100644 --- a/test/parallel/test-stream2-push.js +++ b/test/parallel/test-stream2-push.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var stream = require('stream'); var Readable = stream.Readable; @@ -15,7 +16,7 @@ var stream = new Readable({ encoding: 'utf8' }); -var source = new EE; +var source = new EE(); stream._read = function() { console.error('stream._read'); @@ -80,7 +81,7 @@ writer.on('finish', finish); // now emit some chunks. -var chunk = "asdfg"; +var chunk = 'asdfg'; var set = 0; readStart(); diff --git a/test/parallel/test-stream2-read-sync-stack.js b/test/parallel/test-stream2-read-sync-stack.js index 48b605e46a1865..e912e1039ff558 100644 --- a/test/parallel/test-stream2-read-sync-stack.js +++ b/test/parallel/test-stream2-read-sync-stack.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Readable = require('stream').Readable; diff --git a/test/parallel/test-stream2-readable-empty-buffer-no-eof.js b/test/parallel/test-stream2-readable-empty-buffer-no-eof.js index e71c37e36afcb0..8e4001f8022f1c 100644 --- a/test/parallel/test-stream2-readable-empty-buffer-no-eof.js +++ b/test/parallel/test-stream2-readable-empty-buffer-no-eof.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream2-readable-from-list.js b/test/parallel/test-stream2-readable-from-list.js index 3604ae3ec361cb..f142c49f144fbc 100644 --- a/test/parallel/test-stream2-readable-from-list.js +++ b/test/parallel/test-stream2-readable-from-list.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var fromList = require('_stream_readable')._fromList; @@ -22,7 +23,7 @@ function run() { fn({ same: assert.deepEqual, equal: assert.equal, - end: function () { + end: function() { count--; run(); } @@ -30,7 +31,7 @@ function run() { } // ensure all tests have run -process.on("exit", function () { +process.on('exit', function() { assert.equal(count, 0); }); diff --git a/test/parallel/test-stream2-readable-legacy-drain.js b/test/parallel/test-stream2-readable-legacy-drain.js index 7e8eb6b1ef3898..4218bace2b878f 100644 --- a/test/parallel/test-stream2-readable-legacy-drain.js +++ b/test/parallel/test-stream2-readable-legacy-drain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream2-readable-non-empty-end.js b/test/parallel/test-stream2-readable-non-empty-end.js index d77564cacb7535..46d6f92f2b9df2 100644 --- a/test/parallel/test-stream2-readable-non-empty-end.js +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var Readable = require('_stream_readable'); @@ -5,7 +6,7 @@ var Readable = require('_stream_readable'); var len = 0; var chunks = new Array(10); for (var i = 1; i <= 10; i++) { - chunks[i-1] = new Buffer(i); + chunks[i - 1] = new Buffer(i); len += i; } diff --git a/test/parallel/test-stream2-readable-wrap-empty.js b/test/parallel/test-stream2-readable-wrap-empty.js index c1bc3361f23030..60417ca893300d 100644 --- a/test/parallel/test-stream2-readable-wrap-empty.js +++ b/test/parallel/test-stream2-readable-wrap-empty.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -5,18 +6,18 @@ var Readable = require('_stream_readable'); var EE = require('events').EventEmitter; var oldStream = new EE(); -oldStream.pause = function(){}; -oldStream.resume = function(){}; +oldStream.pause = function() {}; +oldStream.resume = function() {}; var newStream = new Readable().wrap(oldStream); var ended = false; newStream - .on('readable', function(){}) - .on('end', function(){ ended = true; }); + .on('readable', function() {}) + .on('end', function() { ended = true; }); oldStream.emit('end'); -process.on('exit', function(){ +process.on('exit', function() { assert.ok(ended); }); diff --git a/test/parallel/test-stream2-readable-wrap.js b/test/parallel/test-stream2-readable-wrap.js index 71f8a28265bc76..8e3e04b966010f 100644 --- a/test/parallel/test-stream2-readable-wrap.js +++ b/test/parallel/test-stream2-readable-wrap.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -9,8 +10,9 @@ var testRuns = 0, completedRuns = 0; function runTest(highWaterMark, objectMode, produce) { testRuns++; - var old = new EE; - var r = new Readable({ highWaterMark: highWaterMark, objectMode: objectMode }); + var old = new EE(); + var r = new Readable({ highWaterMark: highWaterMark, + objectMode: objectMode }); assert.equal(r, r.wrap(old)); var ended = false; @@ -50,7 +52,8 @@ function runTest(highWaterMark, objectMode, produce) { } } - var w = new Writable({ highWaterMark: highWaterMark * 2, objectMode: objectMode }); + var w = new Writable({ highWaterMark: highWaterMark * 2, + objectMode: objectMode }); var written = []; w._write = function(chunk, encoding, cb) { console.log('_write', chunk); @@ -67,19 +70,19 @@ function runTest(highWaterMark, objectMode, produce) { flow(); - function performAsserts() { + function performAsserts() { assert(ended); assert(oldEnded); assert.deepEqual(written, expected); } } -runTest(100, false, function(){ return new Buffer(100); }); -runTest(10, false, function(){ return new Buffer('xxxxxxxxxx'); }); -runTest(1, true, function(){ return { foo: 'bar' }; }); +runTest(100, false, function() { return new Buffer(100); }); +runTest(10, false, function() { return new Buffer('xxxxxxxxxx'); }); +runTest(1, true, function() { return { foo: 'bar' }; }); var objectChunks = [ 5, 'a', false, 0, '', 'xyz', { x: 4 }, 7, [], 555 ]; -runTest(1, true, function(){ return objectChunks.shift() }); +runTest(1, true, function() { return objectChunks.shift(); }); process.on('exit', function() { assert.equal(testRuns, completedRuns); diff --git a/test/parallel/test-stream2-set-encoding.js b/test/parallel/test-stream2-set-encoding.js index 47f078935bd03d..ea9a315cb1a6e1 100644 --- a/test/parallel/test-stream2-set-encoding.js +++ b/test/parallel/test-stream2-set-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var R = require('_stream_readable'); @@ -23,7 +24,7 @@ function run() { fn({ same: assert.deepEqual, equal: assert.equal, - end: function () { + end: function() { count--; run(); } @@ -31,7 +32,7 @@ function run() { } // ensure all tests have run -process.on("exit", function () { +process.on('exit', function() { assert.equal(count, 0); }); @@ -68,7 +69,7 @@ TestReader.prototype._read = function(n) { var ret = new Buffer(n); ret.fill('a'); - console.log("this.push(ret)", ret) + console.log('this.push(ret)', ret); return this.push(ret); }.bind(this), 1); @@ -146,32 +147,32 @@ test('setEncoding hex with read(13)', function(t) { tr.setEncoding('hex'); var out = []; var expect = - [ "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "16161" ]; + [ '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '16161' ]; tr.on('readable', function flow() { - console.log("readable once") + console.log('readable once'); var chunk; while (null !== (chunk = tr.read(13))) out.push(chunk); }); tr.on('end', function() { - console.log("END") + console.log('END'); t.same(out, expect); t.end(); }); @@ -278,22 +279,22 @@ test('encoding: hex with read(13)', function(t) { var tr = new TestReader(100, { encoding: 'hex' }); var out = []; var expect = - [ "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "16161" ]; + [ '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '16161' ]; tr.on('readable', function flow() { var chunk; diff --git a/test/parallel/test-stream2-transform.js b/test/parallel/test-stream2-transform.js index 3bdef8fbf626e4..e45c913c94f559 100644 --- a/test/parallel/test-stream2-transform.js +++ b/test/parallel/test-stream2-transform.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var PassThrough = require('_stream_passthrough'); @@ -24,7 +25,7 @@ function run() { same: assert.deepEqual, equal: assert.equal, ok: assert, - end: function () { + end: function() { count--; run(); } @@ -32,7 +33,7 @@ function run() { } // ensure all tests have run -process.on("exit", function () { +process.on('exit', function() { assert.equal(count, 0); }); @@ -83,7 +84,7 @@ test('passthrough', function(t) { t.end(); }); -test('object passthrough', function (t) { +test('object passthrough', function(t) { var pt = new PassThrough({ objectMode: true }); pt.write(1); @@ -106,7 +107,7 @@ test('object passthrough', function (t) { }); test('simple transform', function(t) { - var pt = new Transform; + var pt = new Transform(); pt._transform = function(c, e, cb) { var ret = new Buffer(c.length); ret.fill('x'); @@ -154,7 +155,7 @@ test('simple object transform', function(t) { }); test('async passthrough', function(t) { - var pt = new Transform; + var pt = new Transform(); pt._transform = function(chunk, encoding, cb) { setTimeout(function() { pt.push(chunk); @@ -178,7 +179,7 @@ test('async passthrough', function(t) { }); test('assymetric transform (expand)', function(t) { - var pt = new Transform; + var pt = new Transform(); // emit each chunk 2 times. pt._transform = function(chunk, encoding, cb) { @@ -187,7 +188,7 @@ test('assymetric transform (expand)', function(t) { setTimeout(function() { pt.push(chunk); cb(); - }, 10) + }, 10); }, 10); }; @@ -210,7 +211,7 @@ test('assymetric transform (expand)', function(t) { }); test('assymetric transform (compress)', function(t) { - var pt = new Transform; + var pt = new Transform(); // each output is the first char of 3 consecutive chunks, // or whatever's left. @@ -348,10 +349,10 @@ test('passthrough event emission', function(t) { }); test('passthrough event emission reordered', function(t) { - var pt = new PassThrough; + var pt = new PassThrough(); var emits = 0; pt.on('readable', function() { - console.error('emit readable', emits) + console.error('emit readable', emits); emits++; }); @@ -390,7 +391,7 @@ test('passthrough event emission reordered', function(t) { test('passthrough facaded', function(t) { console.error('passthrough facaded'); - var pt = new PassThrough; + var pt = new PassThrough(); var datas = []; pt.on('data', function(chunk) { datas.push(chunk.toString()); @@ -433,8 +434,8 @@ test('object transform (json parse)', function(t) { var objects = [ { foo: 'bar' }, 100, - "string", - { nested: { things: [ { foo: 'bar' }, 100, "string" ] } } + 'string', + { nested: { things: [ { foo: 'bar' }, 100, 'string' ] } } ]; var ended = false; @@ -455,7 +456,7 @@ test('object transform (json parse)', function(t) { process.nextTick(function() { t.ok(ended); t.end(); - }) + }); }); test('object transform (json stringify)', function(t) { @@ -475,8 +476,8 @@ test('object transform (json stringify)', function(t) { var objects = [ { foo: 'bar' }, 100, - "string", - { nested: { things: [ { foo: 'bar' }, 100, "string" ] } } + 'string', + { nested: { things: [ { foo: 'bar' }, 100, 'string' ] } } ]; var ended = false; @@ -497,5 +498,5 @@ test('object transform (json stringify)', function(t) { process.nextTick(function() { t.ok(ended); t.end(); - }) + }); }); diff --git a/test/parallel/test-stream2-unpipe-drain.js b/test/parallel/test-stream2-unpipe-drain.js index 12d1c0648d2345..a430e4a58d6514 100644 --- a/test/parallel/test-stream2-unpipe-drain.js +++ b/test/parallel/test-stream2-unpipe-drain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var stream = require('stream'); @@ -11,11 +12,11 @@ var crypto = require('crypto'); var util = require('util'); function TestWriter() { - stream.Writable.call(this); + stream.Writable.call(this); } util.inherits(TestWriter, stream.Writable); -TestWriter.prototype._write = function (buffer, encoding, callback) { +TestWriter.prototype._write = function(buffer, encoding, callback) { console.log('write called'); // super slow write stream (callback never called) }; @@ -23,12 +24,12 @@ TestWriter.prototype._write = function (buffer, encoding, callback) { var dest = new TestWriter(); function TestReader(id) { - stream.Readable.call(this); - this.reads = 0; + stream.Readable.call(this); + this.reads = 0; } util.inherits(TestReader, stream.Readable); -TestReader.prototype._read = function (size) { +TestReader.prototype._read = function(size) { this.reads += 1; this.push(crypto.randomBytes(size)); }; @@ -38,13 +39,13 @@ var src2 = new TestReader(); src1.pipe(dest); -src1.once('readable', function () { - process.nextTick(function () { +src1.once('readable', function() { + process.nextTick(function() { src2.pipe(dest); - src2.once('readable', function () { - process.nextTick(function () { + src2.once('readable', function() { + process.nextTick(function() { src1.unpipe(dest); }); @@ -53,7 +54,7 @@ src1.once('readable', function () { }); -process.on('exit', function () { +process.on('exit', function() { assert.equal(src1.reads, 2); assert.equal(src2.reads, 2); }); diff --git a/test/parallel/test-stream2-unpipe-leak.js b/test/parallel/test-stream2-unpipe-leak.js index fae2b73ac4f6cf..15b510e7f643cc 100644 --- a/test/parallel/test-stream2-unpipe-leak.js +++ b/test/parallel/test-stream2-unpipe-leak.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var stream = require('stream'); diff --git a/test/parallel/test-stream2-writable.js b/test/parallel/test-stream2-writable.js index d90a2b6f75c468..1d87d7f920c052 100644 --- a/test/parallel/test-stream2-writable.js +++ b/test/parallel/test-stream2-writable.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var W = require('_stream_writable'); var D = require('_stream_duplex'); @@ -46,7 +47,7 @@ function run() { fn({ same: assert.deepEqual, equal: assert.equal, - end: function () { + end: function() { count--; run(); } @@ -54,7 +55,7 @@ function run() { } // ensure all tests have run -process.on("exit", function () { +process.on('exit', function() { assert.equal(count, 0); }); @@ -196,7 +197,7 @@ test('write no bufferize', function(t) { t.end(); }); -test('write callbacks', function (t) { +test('write callbacks', function(t) { var callbacks = chunks.map(function(chunk, i) { return [i, function(er) { callbacks._called[i] = chunk; @@ -225,42 +226,42 @@ test('write callbacks', function (t) { tw.end(); }); -test('end callback', function (t) { +test('end callback', function(t) { var tw = new TestWriter(); - tw.end(function () { + tw.end(function() { t.end(); }); }); -test('end callback with chunk', function (t) { +test('end callback with chunk', function(t) { var tw = new TestWriter(); - tw.end(new Buffer('hello world'), function () { + tw.end(new Buffer('hello world'), function() { t.end(); }); }); -test('end callback with chunk and encoding', function (t) { +test('end callback with chunk and encoding', function(t) { var tw = new TestWriter(); - tw.end('hello world', 'ascii', function () { + tw.end('hello world', 'ascii', function() { t.end(); }); }); -test('end callback after .write() call', function (t) { +test('end callback after .write() call', function(t) { var tw = new TestWriter(); tw.write(new Buffer('hello world')); - tw.end(function () { + tw.end(function() { t.end(); }); }); -test('end callback called after write callback', function (t) { +test('end callback called after write callback', function(t) { var tw = new TestWriter(); var writeCalledback = false; tw.write(new Buffer('hello world'), function() { writeCalledback = true; }); - tw.end(function () { + tw.end(function() { t.equal(writeCalledback, true); t.end(); }); diff --git a/test/parallel/test-stream3-pause-then-read.js b/test/parallel/test-stream3-pause-then-read.js index 737a2f30a1d136..135629a243d66c 100644 --- a/test/parallel/test-stream3-pause-then-read.js +++ b/test/parallel/test-stream3-pause-then-read.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-string-decoder-end.js b/test/parallel/test-string-decoder-end.js index 0bac7a5f28f4d7..f931c6abb9864c 100644 --- a/test/parallel/test-string-decoder-end.js +++ b/test/parallel/test-string-decoder-end.js @@ -1,3 +1,4 @@ +'use strict'; // verify that the string decoder works getting 1 byte at a time, // the whole buffer at once, and that both match the .toString(enc) // result of the entire buffer. diff --git a/test/parallel/test-string-decoder.js b/test/parallel/test-string-decoder.js index dd28ba748b389f..c540ecfacdbf07 100644 --- a/test/parallel/test-string-decoder.js +++ b/test/parallel/test-string-decoder.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var StringDecoder = require('string_decoder').StringDecoder; @@ -54,11 +55,11 @@ function test(encoding, input, expected, singleSequence) { process.stdout.write('.'); if (output !== expected) { var message = - 'Expected "'+unicodeEscape(expected)+'", '+ - 'but got "'+unicodeEscape(output)+'"\n'+ - 'Write sequence: '+JSON.stringify(sequence)+'\n'+ - 'Decoder charBuffer: 0x'+decoder.charBuffer.toString('hex')+'\n'+ - 'Full Decoder State: '+JSON.stringify(decoder, null, 2); + 'Expected "' + unicodeEscape(expected) + '", ' + + 'but got "' + unicodeEscape(output) + '"\n' + + 'Write sequence: ' + JSON.stringify(sequence) + '\n' + + 'Decoder charBuffer: 0x' + decoder.charBuffer.toString('hex') + '\n' + + 'Full Decoder State: ' + JSON.stringify(decoder, null, 2); assert.fail(output, expected, message); } }); @@ -68,7 +69,7 @@ function test(encoding, input, expected, singleSequence) { function unicodeEscape(str) { var r = ''; for (var i = 0; i < str.length; i++) { - r += '\\u'+str.charCodeAt(i).toString(16); + r += '\\u' + str.charCodeAt(i).toString(16); } return r; } @@ -86,7 +87,7 @@ function unicodeEscape(str) { function writeSequences(length, start, sequence) { if (start === undefined) { start = 0; - sequence = [] + sequence = []; } else if (start === length) { return [sequence]; } diff --git a/test/parallel/test-stringbytes-external.js b/test/parallel/test-stringbytes-external.js index 5bc4c945e87705..69ca3c3fa6333b 100644 --- a/test/parallel/test-stringbytes-external.js +++ b/test/parallel/test-stringbytes-external.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); // minimum string size to overflow into external string space @@ -54,7 +55,7 @@ var RADIOS = 2; var PRE_HALF_APEX = Math.ceil(EXTERN_APEX / 2) - RADIOS; var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; -(function () { +(function() { for (var j = 0; j < RADIOS * 2; j += 1) { var datum = b; var slice = datum.slice(0, PRE_HALF_APEX + j); @@ -63,7 +64,7 @@ var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; var pumped_string2 = slice2.toString('hex'); var decoded = new Buffer(pumped_string, 'hex'); - var metadata = "\nEXTERN_APEX=1031913 - pumped_string.length=" + var metadata = '\nEXTERN_APEX=1031913 - pumped_string.length='; metadata += pumped_string.length + '\n'; // the string are the same? @@ -80,7 +81,7 @@ var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; } })(); -(function () { +(function() { for (var j = 0; j < RADIOS * 2; j += 1) { var datum = b; var slice = datum.slice(0, PRE_3OF4_APEX + j); @@ -89,8 +90,8 @@ var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; var pumped_string2 = slice2.toString('base64'); var decoded = new Buffer(pumped_string, 'base64'); - var metadata = "\nEXTERN_APEX=1031913 - data=" + slice.length - metadata += " pumped_string.length=" + pumped_string.length + '\n'; + var metadata = '\nEXTERN_APEX=1031913 - data=" + slice.length'; + metadata += ' pumped_string.length=' + pumped_string.length + '\n'; // the string are the same? for (var k = 0; k < pumped_string.length - 3; ++k) { diff --git a/test/parallel/test-sys.js b/test/parallel/test-sys.js index 8b3ea082b6e135..a5631a5cb16930 100644 --- a/test/parallel/test-sys.js +++ b/test/parallel/test-sys.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tcp-wrap.js b/test/parallel/test-tcp-wrap.js index 6ed8fb44ca806e..93da3e5b3b41c8 100644 --- a/test/parallel/test-tcp-wrap.js +++ b/test/parallel/test-tcp-wrap.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timer-close.js b/test/parallel/test-timer-close.js index b374fe162cfed1..79f06dffa98731 100644 --- a/test/parallel/test-timer-close.js +++ b/test/parallel/test-timer-close.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var t = new (process.binding('timer_wrap').Timer); diff --git a/test/parallel/test-timers-args.js b/test/parallel/test-timers-args.js index 599037b95bc6e6..abb785ea0fc79c 100644 --- a/test/parallel/test-timers-args.js +++ b/test/parallel/test-timers-args.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timers-first-fire.js b/test/parallel/test-timers-first-fire.js index 385724b0b08e44..88460e1e3acb12 100644 --- a/test/parallel/test-timers-first-fire.js +++ b/test/parallel/test-timers-first-fire.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timers-immediate-queue.js b/test/parallel/test-timers-immediate-queue.js index 1c0b095f18c3d6..a71472d46442ab 100644 --- a/test/parallel/test-timers-immediate-queue.js +++ b/test/parallel/test-timers-immediate-queue.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timers-immediate.js b/test/parallel/test-timers-immediate.js index 00652d04060569..bcfc4616ac6264 100644 --- a/test/parallel/test-timers-immediate.js +++ b/test/parallel/test-timers-immediate.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timers-linked-list.js b/test/parallel/test-timers-linked-list.js index 79a9839627c98c..00b2129d126c4a 100644 --- a/test/parallel/test-timers-linked-list.js +++ b/test/parallel/test-timers-linked-list.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var L = require('_linklist'); diff --git a/test/parallel/test-timers-non-integer-delay.js b/test/parallel/test-timers-non-integer-delay.js index 229db3892dba06..a3e5420a5e4858 100644 --- a/test/parallel/test-timers-non-integer-delay.js +++ b/test/parallel/test-timers-non-integer-delay.js @@ -1,3 +1,4 @@ +'use strict'; /* * This test makes sure that non-integer timer delays do not make the process * hang. See https://github.com/joyent/node/issues/8065 and diff --git a/test/parallel/test-timers-ordering.js b/test/parallel/test-timers-ordering.js index 9f40288ec56068..730a78a072c663 100644 --- a/test/parallel/test-timers-ordering.js +++ b/test/parallel/test-timers-ordering.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Timer = process.binding('timer_wrap').Timer; @@ -13,13 +14,15 @@ var start = Timer.now(); var f = function(i) { if (i <= N) { // check order - assert.equal(i, last_i + 1, 'order is broken: ' + i + ' != ' + last_i + ' + 1'); + assert.equal(i, last_i + 1, 'order is broken: ' + i + ' != ' + + last_i + ' + 1'); last_i = i; // check that this iteration is fired at least 1ms later than the previous var now = Timer.now(); console.log(i, now); - assert(now >= last_ts + 1, 'current ts ' + now + ' < prev ts ' + last_ts + ' + 1'); + assert(now >= last_ts + 1, + 'current ts ' + now + ' < prev ts ' + last_ts + ' + 1'); last_ts = now; // schedule next iteration diff --git a/test/parallel/test-timers-this.js b/test/parallel/test-timers-this.js index cacb3f247cc4b8..df710b9cb8d5c9 100644 --- a/test/parallel/test-timers-this.js +++ b/test/parallel/test-timers-this.js @@ -1,37 +1,38 @@ +'use strict'; var assert = require('assert'); var immediateThis, intervalThis, timeoutThis, immediateArgsThis, intervalArgsThis, timeoutArgsThis; -var immediateHandler = setImmediate(function () { +var immediateHandler = setImmediate(function() { immediateThis = this; }); -var immediateArgsHandler = setImmediate(function () { +var immediateArgsHandler = setImmediate(function() { immediateArgsThis = this; -}, "args ..."); +}, 'args ...'); -var intervalHandler = setInterval(function () { +var intervalHandler = setInterval(function() { clearInterval(intervalHandler); intervalThis = this; }); -var intervalArgsHandler = setInterval(function () { +var intervalArgsHandler = setInterval(function() { clearInterval(intervalArgsHandler); intervalArgsThis = this; -}, 0, "args ..."); +}, 0, 'args ...'); -var timeoutHandler = setTimeout(function () { +var timeoutHandler = setTimeout(function() { timeoutThis = this; }); -var timeoutArgsHandler = setTimeout(function () { +var timeoutArgsHandler = setTimeout(function() { timeoutArgsThis = this; -}, 0, "args ..."); +}, 0, 'args ...'); -process.once('exit', function () { +process.once('exit', function() { assert.strictEqual(immediateThis, immediateHandler); assert.strictEqual(immediateArgsThis, immediateArgsHandler); diff --git a/test/parallel/test-timers-uncaught-exception.js b/test/parallel/test-timers-uncaught-exception.js index 4e137427939654..794b3b923be1df 100644 --- a/test/parallel/test-timers-uncaught-exception.js +++ b/test/parallel/test-timers-uncaught-exception.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timers-unref-call.js b/test/parallel/test-timers-unref-call.js index 4f7865b8457601..b348330d200d65 100644 --- a/test/parallel/test-timers-unref-call.js +++ b/test/parallel/test-timers-unref-call.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var Timer = process.binding('timer_wrap').Timer; diff --git a/test/parallel/test-timers-unref-leak.js b/test/parallel/test-timers-unref-leak.js index c8f958a47c40d2..55907d9bc4898d 100644 --- a/test/parallel/test-timers-unref-leak.js +++ b/test/parallel/test-timers-unref-leak.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var called = 0; diff --git a/test/parallel/test-timers-unref.js b/test/parallel/test-timers-unref.js index 2f750228a4ef3f..ab2e33acd21019 100644 --- a/test/parallel/test-timers-unref.js +++ b/test/parallel/test-timers-unref.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -53,9 +54,14 @@ setInterval(function() { })(); process.on('exit', function() { - assert.strictEqual(interval_fired, false, 'Interval should not fire'); - assert.strictEqual(timeout_fired, false, 'Timeout should not fire'); - assert.strictEqual(unref_timer, true, 'An unrefd timeout should still fire'); - assert.strictEqual(unref_interval, true, 'An unrefd interval should still fire'); - assert.strictEqual(unref_callbacks, 1, 'Callback should only run once'); + assert.strictEqual(interval_fired, false, + 'Interval should not fire'); + assert.strictEqual(timeout_fired, false, + 'Timeout should not fire'); + assert.strictEqual(unref_timer, true, + 'An unrefd timeout should still fire'); + assert.strictEqual(unref_interval, true, + 'An unrefd interval should still fire'); + assert.strictEqual(unref_callbacks, 1, + 'Callback should only run once'); }); diff --git a/test/parallel/test-timers-unrefd-interval-still-fires.js b/test/parallel/test-timers-unrefd-interval-still-fires.js index 3ea94454cfdb49..50a473b9c8b4b8 100644 --- a/test/parallel/test-timers-unrefd-interval-still-fires.js +++ b/test/parallel/test-timers-unrefd-interval-still-fires.js @@ -1,3 +1,4 @@ +'use strict'; /* * This test is a regression test for joyent/node#8900. */ diff --git a/test/parallel/test-timers-zero-timeout.js b/test/parallel/test-timers-zero-timeout.js index 939b8db1bb30db..1c84814363a641 100644 --- a/test/parallel/test-timers-zero-timeout.js +++ b/test/parallel/test-timers-zero-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timers.js b/test/parallel/test-timers.js index dad1bcc69389a0..e784e262959d97 100644 --- a/test/parallel/test-timers.js +++ b/test/parallel/test-timers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-0-dns-altname.js b/test/parallel/test-tls-0-dns-altname.js index 0d01805154255a..fd10206a126359 100644 --- a/test/parallel/test-tls-0-dns-altname.js +++ b/test/parallel/test-tls-0-dns-altname.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -31,8 +32,8 @@ var server = tls.createServer({ assert.equal(cert.subjectaltname, 'DNS:google.com\0.evil.com, ' + 'DNS:just-another.com, ' + - 'IP Address:8.8.8.8, '+ - 'IP Address:8.8.4.4, '+ + 'IP Address:8.8.8.8, ' + + 'IP Address:8.8.4.4, ' + 'DNS:last.com'); c.write('ok'); }); diff --git a/test/parallel/test-tls-alert-handling.js b/test/parallel/test-tls-alert-handling.js new file mode 100644 index 00000000000000..ed8999b6b7a409 --- /dev/null +++ b/test/parallel/test-tls-alert-handling.js @@ -0,0 +1,91 @@ +'use strict'; +var common = require('../common'); +var assert = require('assert'); + +if (!common.opensslCli) { + console.error('Skipping because node compiled without OpenSSL CLI.'); + process.exit(0); +} + +if (!common.hasCrypto) { + console.log('1..0 # Skipped: missing crypto'); + process.exit(); +} + +var tls = require('tls'); +var net = require('net'); +var fs = require('fs'); + +var success = false; + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +var opts = { + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert') +}; + +var max_iter = 20; +var iter = 0; + +var server = tls.createServer(opts, function(s) { + s.pipe(s); + s.on('error', function(e) { + // ignore error + }); +}); + +server.listen(common.PORT, function() { + sendClient(); +}); + + +function sendClient() { + var client = tls.connect(common.PORT, { + rejectUnauthorized: false + }); + client.on('data', function(chunk) { + if (iter++ === 2) sendBADTLSRecord(); + if (iter < max_iter) { + client.write('a'); + return; + } + client.end(); + server.close(); + success = true; + }); + client.write('a'); + client.on('error', function(e) { + // ignore error + }); + client.on('close', function() { + server.close(); + }); +} + + +function sendBADTLSRecord() { + var BAD_RECORD = new Buffer([0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); + var socket = net.connect(common.PORT); + var client = tls.connect({ + socket: socket, + rejectUnauthorized: false + }, function() { + socket.write(BAD_RECORD); + socket.end(); + }); + client.on('error', function(e) { + // ignore error + }); +} + +process.on('exit', function() { + assert(iter === max_iter); + assert(success); +}); diff --git a/test/parallel/test-tls-alert.js b/test/parallel/test-tls-alert.js index a96a104f24d3d2..97087d0b3b4c03 100644 --- a/test/parallel/test-tls-alert.js +++ b/test/parallel/test-tls-alert.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -30,7 +31,8 @@ var server = tls.Server({ key: loadPEM('agent2-key'), cert:loadPEM('agent2-cert') }, null).listen(common.PORT, function() { - var args = ['s_client', '-quiet', '-tls1_1','-connect', '127.0.0.1:' + common.PORT]; + var args = ['s_client', '-quiet', '-tls1_1', + '-connect', '127.0.0.1:' + common.PORT]; var client = spawn(common.opensslCli, args); var out = ''; client.stderr.setEncoding('utf8'); diff --git a/test/parallel/test-tls-cert-regression.js b/test/parallel/test-tls-cert-regression.js index c7b1742856aead..24bc4242749f6c 100644 --- a/test/parallel/test-tls-cert-regression.js +++ b/test/parallel/test-tls-cert-regression.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-tls-check-server-identity.js b/test/parallel/test-tls-check-server-identity.js index 85413b62e3d591..e40cbb0f9da137 100644 --- a/test/parallel/test-tls-check-server-identity.js +++ b/test/parallel/test-tls-check-server-identity.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); diff --git a/test/parallel/test-tls-client-abort.js b/test/parallel/test-tls-client-abort.js index a2a4bba5bbd28c..25e44716c1d700 100644 --- a/test/parallel/test-tls-client-abort.js +++ b/test/parallel/test-tls-client-abort.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-client-abort2.js b/test/parallel/test-tls-client-abort2.js index 7874d3d25acd56..b64482b58dc03c 100644 --- a/test/parallel/test-tls-client-abort2.js +++ b/test/parallel/test-tls-client-abort2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-client-default-ciphers.js b/test/parallel/test-tls-client-default-ciphers.js index e1422bac6f3662..5da57173315a09 100644 --- a/test/parallel/test-tls-client-default-ciphers.js +++ b/test/parallel/test-tls-client-default-ciphers.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); @@ -15,7 +16,7 @@ function test1() { tls.createSecureContext = function(options) { ciphers = options.ciphers; throw new Done(); - } + }; try { var s = tls.connect(common.PORT); diff --git a/test/parallel/test-tls-client-destroy-soon.js b/test/parallel/test-tls-client-destroy-soon.js index 08b261a7222e0c..6a1a899103d9e9 100644 --- a/test/parallel/test-tls-client-destroy-soon.js +++ b/test/parallel/test-tls-client-destroy-soon.js @@ -1,3 +1,4 @@ +'use strict'; // Create an ssl server. First connection, validate that not resume. // Cache session and close connection. Use session on second connection. // ASSERT resumption. diff --git a/test/parallel/test-tls-client-reject.js b/test/parallel/test-tls-client-reject.js index 887ff283ad0a52..9e09493c6a464d 100644 --- a/test/parallel/test-tls-client-reject.js +++ b/test/parallel/test-tls-client-reject.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-client-resume.js b/test/parallel/test-tls-client-resume.js index 75d96b69335d84..8b36224a7f2a37 100644 --- a/test/parallel/test-tls-client-resume.js +++ b/test/parallel/test-tls-client-resume.js @@ -1,3 +1,4 @@ +'use strict'; // Create an ssl server. First connection, validate that not resume. // Cache session and close connection. Use session on second connection. // ASSERT resumption. diff --git a/test/parallel/test-tls-client-verify.js b/test/parallel/test-tls-client-verify.js index bdbde6f9931175..f206929f59560c 100644 --- a/test/parallel/test-tls-client-verify.js +++ b/test/parallel/test-tls-client-verify.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-close-notify.js b/test/parallel/test-tls-close-notify.js index 3960a62694042e..cfb9aab0d9789f 100644 --- a/test/parallel/test-tls-close-notify.js +++ b/test/parallel/test-tls-close-notify.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-tls-connect-given-socket.js b/test/parallel/test-tls-connect-given-socket.js index e309d824aba201..9e8170b13af1b7 100644 --- a/test/parallel/test-tls-connect-given-socket.js +++ b/test/parallel/test-tls-connect-given-socket.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-connect-no-host.js b/test/parallel/test-tls-connect-no-host.js index 41aac1acabd781..30d78dfa6ed548 100644 --- a/test/parallel/test-tls-connect-no-host.js +++ b/test/parallel/test-tls-connect-no-host.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.hasCrypto) { @@ -29,6 +30,6 @@ var socket = tls.connect({ // Error: Hostname/IP doesn't match certificate's altnames: // "Host: undefined. is not cert's CN: localhost" }, function() { - assert(socket.authorized); - process.exit(); + assert(socket.authorized); + process.exit(); }); diff --git a/test/parallel/test-tls-connect-pipe.js b/test/parallel/test-tls-connect-pipe.js index 70daa0d75ab047..bded532720f98b 100644 --- a/test/parallel/test-tls-connect-pipe.js +++ b/test/parallel/test-tls-connect-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-connect-simple.js b/test/parallel/test-tls-connect-simple.js index 04eb5f408a6b81..feaa7c887b1e30 100644 --- a/test/parallel/test-tls-connect-simple.js +++ b/test/parallel/test-tls-connect-simple.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-connect-stream-writes.js b/test/parallel/test-tls-connect-stream-writes.js new file mode 100644 index 00000000000000..4187c9b439e2f1 --- /dev/null +++ b/test/parallel/test-tls-connect-stream-writes.js @@ -0,0 +1,66 @@ +'use strict'; +var assert = require('assert'), + fs = require('fs'), + path = require('path'), + tls = require('tls'), + stream = require('stream'), + net = require('net'); + +var common = require('../common'); + +var server; +var cert_dir = path.resolve(__dirname, '../fixtures'), + options = { key: fs.readFileSync(cert_dir + '/test_key.pem'), + cert: fs.readFileSync(cert_dir + '/test_cert.pem'), + ca: [ fs.readFileSync(cert_dir + '/test_ca.pem') ], + ciphers: 'AES256-GCM-SHA384' }; +var content = 'hello world'; +var recv_bufs = []; +var send_data = ''; +server = tls.createServer(options, function(s) { + s.on('data', function(c) { + recv_bufs.push(c); + }); +}); +server.listen(common.PORT, function() { + var raw = net.connect(common.PORT); + + var pending = false; + raw.on('readable', function() { + if (pending) + p._read(); + }); + + var p = new stream.Duplex({ + read: function read() { + pending = false; + + var chunk = raw.read(); + if (chunk) { + this.push(chunk); + } else { + pending = true; + } + }, + write: function write(data, enc, cb) { + raw.write(data, enc, cb); + } + }); + + var socket = tls.connect({ + socket: p, + rejectUnauthorized: false + }, function() { + for (var i = 0; i < 50; ++i) { + socket.write(content); + send_data += content; + } + socket.end(); + server.close(); + }); +}); + +process.on('exit', function() { + var recv_data = (Buffer.concat(recv_bufs)).toString(); + assert.strictEqual(send_data, recv_data); +}); diff --git a/test/parallel/test-tls-connect.js b/test/parallel/test-tls-connect.js index f74dc089533c00..160d874bed3355 100644 --- a/test/parallel/test-tls-connect.js +++ b/test/parallel/test-tls-connect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-delayed-attach.js b/test/parallel/test-tls-delayed-attach.js index fba10ceffd97bd..00731592445f04 100644 --- a/test/parallel/test-tls-delayed-attach.js +++ b/test/parallel/test-tls-delayed-attach.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-dhe.js b/test/parallel/test-tls-dhe.js index eb59c84957b52d..92fff3f221b65f 100644 --- a/test/parallel/test-tls-dhe.js +++ b/test/parallel/test-tls-dhe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -61,8 +62,9 @@ function test(keylen, expectedCipher, cb) { } function test512() { - test(512, 'DHE-RSA-AES128-SHA256', test1024); - ntests++; + assert.throws(function() { + test(512, 'DHE-RSA-AES128-SHA256', null); + }, /DH parameter is less than 1024 bits/); } function test1024() { @@ -76,12 +78,13 @@ function test2048() { } function testError() { - test('error', 'ECDHE-RSA-AES128-SHA256', null); + test('error', 'ECDHE-RSA-AES128-SHA256', test512); ntests++; } -test512(); +test1024(); process.on('exit', function() { assert.equal(ntests, nsuccess); + assert.equal(ntests, 3); }); diff --git a/test/parallel/test-tls-ecdh-disable.js b/test/parallel/test-tls-ecdh-disable.js index 1799ec454c0cec..1ed4ea35738d5f 100644 --- a/test/parallel/test-tls-ecdh-disable.js +++ b/test/parallel/test-tls-ecdh-disable.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-ecdh.js b/test/parallel/test-tls-ecdh.js index 042491672ff407..cd144d79e0e073 100644 --- a/test/parallel/test-tls-ecdh.js +++ b/test/parallel/test-tls-ecdh.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-econnreset.js b/test/parallel/test-tls-econnreset.js index c339fc5be60a61..f451df68470c53 100644 --- a/test/parallel/test-tls-econnreset.js +++ b/test/parallel/test-tls-econnreset.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-fast-writing.js b/test/parallel/test-tls-fast-writing.js index e9245aa0d5eae1..24e8bfc6886f16 100644 --- a/test/parallel/test-tls-fast-writing.js +++ b/test/parallel/test-tls-fast-writing.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-friendly-error-message.js b/test/parallel/test-tls-friendly-error-message.js index efff0c66a3169b..b2f2de137da8fa 100644 --- a/test/parallel/test-tls-friendly-error-message.js +++ b/test/parallel/test-tls-friendly-error-message.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-getcipher.js b/test/parallel/test-tls-getcipher.js index 414010c0336e7e..12e3b8f9c64ecf 100644 --- a/test/parallel/test-tls-getcipher.js +++ b/test/parallel/test-tls-getcipher.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-handshake-nohang.js b/test/parallel/test-tls-handshake-nohang.js index 73869892fb9ff7..181d6408e05abc 100644 --- a/test/parallel/test-tls-handshake-nohang.js +++ b/test/parallel/test-tls-handshake-nohang.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-hello-parser-failure.js b/test/parallel/test-tls-hello-parser-failure.js index 463fdaa44b53e3..3ed82c536a9e7a 100644 --- a/test/parallel/test-tls-hello-parser-failure.js +++ b/test/parallel/test-tls-hello-parser-failure.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -40,7 +41,7 @@ var server = tls.createServer(options, function(c) { } }); - client.on('close', function (hadError) { + client.on('close', function(hadError) { assert.strictEqual(hadError, true, 'Client never errored'); }); }); diff --git a/test/parallel/test-tls-inception.js b/test/parallel/test-tls-inception.js index 7fd0b813d6d4c4..76e6fe077ffef9 100644 --- a/test/parallel/test-tls-inception.js +++ b/test/parallel/test-tls-inception.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -20,7 +21,7 @@ options = { }; // the "proxy" server -a = tls.createServer(options, function (socket) { +a = tls.createServer(options, function(socket) { var options = { host: '127.0.0.1', port: b.address().port, @@ -36,16 +37,16 @@ a = tls.createServer(options, function (socket) { }); // the "target" server -b = tls.createServer(options, function (socket) { +b = tls.createServer(options, function(socket) { socket.end('hello'); }); -process.on('exit', function () { +process.on('exit', function() { assert(gotHello); }); -a.listen(common.PORT, function () { - b.listen(common.PORT + 1, function () { +a.listen(common.PORT, function() { + b.listen(common.PORT + 1, function() { options = { host: '127.0.0.1', port: a.address().port, @@ -58,11 +59,11 @@ a.listen(common.PORT, function () { rejectUnauthorized: false }); ssl.setEncoding('utf8'); - ssl.once('data', function (data) { + ssl.once('data', function(data) { assert.equal('hello', data); gotHello = true; }); - ssl.on('end', function () { + ssl.on('end', function() { ssl.end(); a.close(); b.close(); diff --git a/test/parallel/test-tls-interleave.js b/test/parallel/test-tls-interleave.js index 96a7a600381d1b..e726e16998a908 100644 --- a/test/parallel/test-tls-interleave.js +++ b/test/parallel/test-tls-interleave.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-invoke-queued.js b/test/parallel/test-tls-invoke-queued.js index c6e94158829c35..f9607e1f4fa928 100644 --- a/test/parallel/test-tls-invoke-queued.js +++ b/test/parallel/test-tls-invoke-queued.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-js-stream.js b/test/parallel/test-tls-js-stream.js index 12c3381cb4fd60..e156f446f57de9 100644 --- a/test/parallel/test-tls-js-stream.js +++ b/test/parallel/test-tls-js-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-junk-closes-server.js b/test/parallel/test-tls-junk-closes-server.js index 3fd129cbf6d470..01a83ef214e0b6 100644 --- a/test/parallel/test-tls-junk-closes-server.js +++ b/test/parallel/test-tls-junk-closes-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.hasCrypto) { diff --git a/test/parallel/test-tls-key-mismatch.js b/test/parallel/test-tls-key-mismatch.js index cd7ad605a89675..35da4687493a21 100644 --- a/test/parallel/test-tls-key-mismatch.js +++ b/test/parallel/test-tls-key-mismatch.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-max-send-fragment.js b/test/parallel/test-tls-max-send-fragment.js index 4033b308acdb71..3e41cfa45c7d30 100644 --- a/test/parallel/test-tls-max-send-fragment.js +++ b/test/parallel/test-tls-max-send-fragment.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-multi-key.js b/test/parallel/test-tls-multi-key.js index 85ff5e808cfe16..76aa97d1ff3daf 100644 --- a/test/parallel/test-tls-multi-key.js +++ b/test/parallel/test-tls-multi-key.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-no-cert-required.js b/test/parallel/test-tls-no-cert-required.js index 75afc110999aa6..02bbb6b664a2cf 100644 --- a/test/parallel/test-tls-no-cert-required.js +++ b/test/parallel/test-tls-no-cert-required.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.hasCrypto) { diff --git a/test/parallel/test-tls-no-rsa-key.js b/test/parallel/test-tls-no-rsa-key.js index 389cd329c6fd4f..fd64438ead7f4e 100644 --- a/test/parallel/test-tls-no-rsa-key.js +++ b/test/parallel/test-tls-no-rsa-key.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-no-sslv23.js b/test/parallel/test-tls-no-sslv23.js index 56fd89f76a3225..931bf5dba050b9 100644 --- a/test/parallel/test-tls-no-sslv23.js +++ b/test/parallel/test-tls-no-sslv23.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-no-sslv3.js b/test/parallel/test-tls-no-sslv3.js index 0fc0dcc3ae3fea..4e1975a1e00a25 100644 --- a/test/parallel/test-tls-no-sslv3.js +++ b/test/parallel/test-tls-no-sslv3.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-npn-server-client.js b/test/parallel/test-tls-npn-server-client.js index 406751b0289cb5..bebb6799b9f49c 100644 --- a/test/parallel/test-tls-npn-server-client.js +++ b/test/parallel/test-tls-npn-server-client.js @@ -1,3 +1,4 @@ +'use strict'; if (!process.features.tls_npn) { console.error('Skipping because node compiled without OpenSSL or ' + 'with old OpenSSL version.'); diff --git a/test/parallel/test-tls-ocsp-callback.js b/test/parallel/test-tls-ocsp-callback.js index a9ac6ffa17d359..73f1c5772a59fb 100644 --- a/test/parallel/test-tls-ocsp-callback.js +++ b/test/parallel/test-tls-ocsp-callback.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!process.features.tls_ocsp) { diff --git a/test/parallel/test-tls-on-empty-socket.js b/test/parallel/test-tls-on-empty-socket.js index f4866701e23eb5..8d95a997200786 100644 --- a/test/parallel/test-tls-on-empty-socket.js +++ b/test/parallel/test-tls-on-empty-socket.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-over-http-tunnel.js b/test/parallel/test-tls-over-http-tunnel.js index c851f02a575259..cf7ab78685c364 100644 --- a/test/parallel/test-tls-over-http-tunnel.js +++ b/test/parallel/test-tls-over-http-tunnel.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-passphrase.js b/test/parallel/test-tls-passphrase.js index f1253ee51b986f..ce68fce5f02b99 100644 --- a/test/parallel/test-tls-passphrase.js +++ b/test/parallel/test-tls-passphrase.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-pause.js b/test/parallel/test-tls-pause.js index 95f293d234e803..f9d68f1395420a 100644 --- a/test/parallel/test-tls-pause.js +++ b/test/parallel/test-tls-pause.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-peer-certificate-encoding.js b/test/parallel/test-tls-peer-certificate-encoding.js index 536bfae2031934..533b9126cda573 100644 --- a/test/parallel/test-tls-peer-certificate-encoding.js +++ b/test/parallel/test-tls-peer-certificate-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-peer-certificate-multi-keys.js b/test/parallel/test-tls-peer-certificate-multi-keys.js index 3488600e272091..fde55af50be2bf 100644 --- a/test/parallel/test-tls-peer-certificate-multi-keys.js +++ b/test/parallel/test-tls-peer-certificate-multi-keys.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-peer-certificate.js b/test/parallel/test-tls-peer-certificate.js index a1a19d7035d3ca..8164154779f998 100644 --- a/test/parallel/test-tls-peer-certificate.js +++ b/test/parallel/test-tls-peer-certificate.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -36,13 +37,13 @@ server.listen(common.PORT, function() { common.debug(util.inspect(peerCert)); assert.equal(peerCert.subject.emailAddress, '[email protected]'); - assert.equal(peerCert.serialNumber, '9A84ABCFB8A72ABE'); + assert.equal(peerCert.serialNumber, '9A84ABCFB8A72AC0'); assert.deepEqual(peerCert.infoAccess['OCSP - URI'], [ 'http://ocsp.nodejs.org/' ]); var issuer = peerCert.issuerCertificate; assert.ok(issuer.issuerCertificate === issuer); - assert.equal(issuer.serialNumber, 'B5090C899FC2FF93'); + assert.equal(issuer.serialNumber, '8DF21C01468AF393'); verified = true; server.close(); }); diff --git a/test/parallel/test-tls-request-timeout.js b/test/parallel/test-tls-request-timeout.js index 10a14696c43a71..dce27a2591289b 100644 --- a/test/parallel/test-tls-request-timeout.js +++ b/test/parallel/test-tls-request-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-securepair-server.js b/test/parallel/test-tls-securepair-server.js index 99bd4dd6f92606..7ddba939bacd30 100644 --- a/test/parallel/test-tls-securepair-server.js +++ b/test/parallel/test-tls-securepair-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-server-verify.js b/test/parallel/test-tls-server-verify.js index 0204bc5d1f074e..f30134f04ac0a5 100644 --- a/test/parallel/test-tls-server-verify.js +++ b/test/parallel/test-tls-server-verify.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.opensslCli) { diff --git a/test/parallel/test-tls-session-cache.js b/test/parallel/test-tls-session-cache.js index 8ba2deec2e2ebd..7ba063a3a029af 100644 --- a/test/parallel/test-tls-session-cache.js +++ b/test/parallel/test-tls-session-cache.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.opensslCli) { diff --git a/test/parallel/test-tls-set-ciphers.js b/test/parallel/test-tls-set-ciphers.js index ba4341633b0895..f5284c1b58b4ac 100644 --- a/test/parallel/test-tls-set-ciphers.js +++ b/test/parallel/test-tls-set-ciphers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.opensslCli) { diff --git a/test/parallel/test-tls-set-encoding.js b/test/parallel/test-tls-set-encoding.js index d73572c93ba0f7..fa0d72b5ad4bd7 100644 --- a/test/parallel/test-tls-set-encoding.js +++ b/test/parallel/test-tls-set-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-sni-option.js b/test/parallel/test-tls-sni-option.js index 3768c7eaac8f48..68ef2caa9819d3 100644 --- a/test/parallel/test-tls-sni-option.js +++ b/test/parallel/test-tls-sni-option.js @@ -1,3 +1,4 @@ +'use strict'; if (!process.features.tls_sni) { console.error('Skipping because node compiled without OpenSSL or ' + 'with old OpenSSL version.'); @@ -146,6 +147,6 @@ process.on('exit', function() { assert.deepEqual(serverResults, ['a.example.com', 'b.example.com', 'c.wrong.com', null]); assert.deepEqual(clientResults, [true, true, false, false]); - assert.deepEqual(clientErrors, [null, null, null, "socket hang up"]); - assert.deepEqual(serverErrors, [null, null, null, "Invalid SNI context"]); + assert.deepEqual(clientErrors, [null, null, null, 'socket hang up']); + assert.deepEqual(serverErrors, [null, null, null, 'Invalid SNI context']); }); diff --git a/test/parallel/test-tls-sni-server-client.js b/test/parallel/test-tls-sni-server-client.js index 7a1d09b9c2ef07..dec829face184e 100644 --- a/test/parallel/test-tls-sni-server-client.js +++ b/test/parallel/test-tls-sni-server-client.js @@ -1,3 +1,4 @@ +'use strict'; if (!process.features.tls_sni) { console.error('Skipping because node compiled without OpenSSL or ' + 'with old OpenSSL version.'); @@ -35,6 +36,11 @@ var SNIContexts = { 'asterisk.test.com': { key: loadPEM('agent3-key'), cert: loadPEM('agent3-cert') + }, + 'chain.example.com': { + key: loadPEM('agent6-key'), + // NOTE: Contains ca3 chain cert + cert: loadPEM('agent6-cert') } }; @@ -42,32 +48,29 @@ var serverPort = common.PORT; var clientsOptions = [{ port: serverPort, - key: loadPEM('agent1-key'), - cert: loadPEM('agent1-cert'), ca: [loadPEM('ca1-cert')], servername: 'a.example.com', rejectUnauthorized: false }, { port: serverPort, - key: loadPEM('agent2-key'), - cert: loadPEM('agent2-cert'), ca: [loadPEM('ca2-cert')], servername: 'b.test.com', rejectUnauthorized: false }, { port: serverPort, - key: loadPEM('agent2-key'), - cert: loadPEM('agent2-cert'), ca: [loadPEM('ca2-cert')], servername: 'a.b.test.com', rejectUnauthorized: false }, { port: serverPort, - key: loadPEM('agent3-key'), - cert: loadPEM('agent3-cert'), ca: [loadPEM('ca1-cert')], servername: 'c.wrong.com', rejectUnauthorized: false +}, { + port: serverPort, + ca: [loadPEM('ca1-cert')], + servername: 'chain.example.com', + rejectUnauthorized: false }]; var serverResults = [], @@ -79,6 +82,7 @@ var server = tls.createServer(serverOptions, function(c) { server.addContext('a.example.com', SNIContexts['a.example.com']); server.addContext('*.test.com', SNIContexts['asterisk.test.com']); +server.addContext('chain.example.com', SNIContexts['chain.example.com']); server.listen(serverPort, startTest); @@ -105,7 +109,9 @@ function startTest() { } process.on('exit', function() { - assert.deepEqual(serverResults, ['a.example.com', 'b.test.com', - 'a.b.test.com', 'c.wrong.com']); - assert.deepEqual(clientResults, [true, true, false, false]); + assert.deepEqual(serverResults, [ + 'a.example.com', 'b.test.com', 'a.b.test.com', 'c.wrong.com', + 'chain.example.com' + ]); + assert.deepEqual(clientResults, [true, true, false, false, true]); }); diff --git a/test/parallel/test-tls-ticket-cluster.js b/test/parallel/test-tls-ticket-cluster.js index 1b20e5ac8e90d9..a9798df0597945 100644 --- a/test/parallel/test-tls-ticket-cluster.js +++ b/test/parallel/test-tls-ticket-cluster.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-ticket.js b/test/parallel/test-tls-ticket.js index cf5cae9c8a8f7c..450f6b54a52809 100644 --- a/test/parallel/test-tls-ticket.js +++ b/test/parallel/test-tls-ticket.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -31,7 +32,9 @@ function createServer() { return server; } -var servers = [ createServer(), createServer(), createServer(), createServer(), createServer(), createServer() ]; +var servers = [ createServer(), createServer(), + createServer(), createServer(), + createServer(), createServer() ]; // Create one TCP server and balance sockets to multiple TLS server instances var shared = net.createServer(function(c) { diff --git a/test/parallel/test-tls-timeout-server-2.js b/test/parallel/test-tls-timeout-server-2.js index a16ce33167bb48..e752c004d3abbb 100644 --- a/test/parallel/test-tls-timeout-server-2.js +++ b/test/parallel/test-tls-timeout-server-2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-timeout-server.js b/test/parallel/test-tls-timeout-server.js index 47845fae39751c..4a9265079bf136 100644 --- a/test/parallel/test-tls-timeout-server.js +++ b/test/parallel/test-tls-timeout-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-wrap-timeout.js b/test/parallel/test-tls-wrap-timeout.js index 3013f68886597f..87534cfd2e95ef 100644 --- a/test/parallel/test-tls-wrap-timeout.js +++ b/test/parallel/test-tls-wrap-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-zero-clear-in.js b/test/parallel/test-tls-zero-clear-in.js index 38b21f401e21a4..6eeba92585603f 100644 --- a/test/parallel/test-tls-zero-clear-in.js +++ b/test/parallel/test-tls-zero-clear-in.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tty-stdout-end.js b/test/parallel/test-tty-stdout-end.js index a2f3ad12f4aca7..190acae42870a9 100644 --- a/test/parallel/test-tty-stdout-end.js +++ b/test/parallel/test-tty-stdout-end.js @@ -1,3 +1,4 @@ +'use strict'; // Can't test this when 'make test' doesn't assign a tty to the stdout. var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tty-wrap.js b/test/parallel/test-tty-wrap.js index 1cd014992dcad6..370c959ea297a6 100644 --- a/test/parallel/test-tty-wrap.js +++ b/test/parallel/test-tty-wrap.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-umask.js b/test/parallel/test-umask.js index 84c34412189d25..94d3a1d06f9c6c 100644 --- a/test/parallel/test-umask.js +++ b/test/parallel/test-umask.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-url.js b/test/parallel/test-url.js index 121d6caaf612e3..e0587ae743d9b1 100644 --- a/test/parallel/test-url.js +++ b/test/parallel/test-url.js @@ -1,3 +1,5 @@ +/* eslint-disable max-len */ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -553,7 +555,6 @@ var parseTests = { 'http://bucket_name.s3.amazonaws.com/image.jpg': { protocol: 'http:', - 'slashes': true, slashes: true, host: 'bucket_name.s3.amazonaws.com', hostname: 'bucket_name.s3.amazonaws.com', @@ -857,11 +858,11 @@ var parseTests = { }; for (var u in parseTests) { - var actual = url.parse(u), - spaced = url.parse(' \t ' + u + '\n\t'); - expected = parseTests[u]; + var actual = url.parse(u); + var spaced = url.parse(' \t ' + u + '\n\t'); + var expected = parseTests[u]; - Object.keys(actual).forEach(function (i) { + Object.keys(actual).forEach(function(i) { if (expected[i] === undefined && actual[i] === null) { expected[i] = null; } @@ -1097,7 +1098,7 @@ var formatTests = { query: { foo: 'theA1' }, - hash: "#bar" + hash: '#bar' }, // `#`,`?` in path + `#` in query @@ -1107,7 +1108,7 @@ var formatTests = { query: { foo: 'the#1' }, - hash: "#bar" + hash: '#bar' }, // `?` and `#` in path and search @@ -1269,7 +1270,7 @@ var relativeTests2 = [ ['g?y#s', bases[0], 'http://a/b/c/g?y#s'], [';x', bases[0], 'http://a/b/c/;x'], ['g;x', bases[0], 'http://a/b/c/g;x'], - ['g;x?y#s' , bases[0], 'http://a/b/c/g;x?y#s'], + ['g;x?y#s', bases[0], 'http://a/b/c/g;x?y#s'], // changed with RFC 2396bis //('', bases[0], CURRENT_DOC_URI], ['', bases[0], 'http://a/b/c/d;p?q'], @@ -1280,7 +1281,7 @@ var relativeTests2 = [ ['../g', bases[0], 'http://a/b/g'], ['../..', bases[0], 'http://a/'], ['../../', bases[0], 'http://a/'], - ['../../g' , bases[0], 'http://a/g'], + ['../../g', bases[0], 'http://a/g'], ['../../../g', bases[0], ('http://a/../g', 'http://a/g')], ['../../../../g', bases[0], ('http://a/../../g', 'http://a/g')], // changed with RFC 2396bis @@ -1319,16 +1320,16 @@ var relativeTests2 = [ //('?y', bases[1], 'http://a/b/c/?y'], ['?y', bases[1], 'http://a/b/c/d;p?y'], ['g?y', bases[1], 'http://a/b/c/g?y'], - ['g?y/./x' , bases[1], 'http://a/b/c/g?y/./x'], + ['g?y/./x', bases[1], 'http://a/b/c/g?y/./x'], ['g?y/../x', bases[1], 'http://a/b/c/g?y/../x'], ['g#s', bases[1], 'http://a/b/c/g#s'], - ['g#s/./x' , bases[1], 'http://a/b/c/g#s/./x'], + ['g#s/./x', bases[1], 'http://a/b/c/g#s/./x'], ['g#s/../x', bases[1], 'http://a/b/c/g#s/../x'], ['./', bases[1], 'http://a/b/c/'], ['../', bases[1], 'http://a/b/'], ['../g', bases[1], 'http://a/b/g'], ['../../', bases[1], 'http://a/'], - ['../../g' , bases[1], 'http://a/g'], + ['../../g', bases[1], 'http://a/g'], // http://gbiv.com/protocols/uri/test/rel_examples3.html // slashes in path params @@ -1345,7 +1346,7 @@ var relativeTests2 = [ ['../', bases[2], 'http://a/b/c/'], ['../g', bases[2], 'http://a/b/c/g'], ['../../', bases[2], 'http://a/b/'], - ['../../g' , bases[2], 'http://a/b/g'], + ['../../g', bases[2], 'http://a/b/g'], // http://gbiv.com/protocols/uri/test/rel_examples4.html // double and triple slash, unknown scheme @@ -1362,7 +1363,7 @@ var relativeTests2 = [ ['../g', bases[3], 'fred:///s//a/g'], ['../../', bases[3], 'fred:///s//'], - ['../../g' , bases[3], 'fred:///s//g'], + ['../../g', bases[3], 'fred:///s//g'], ['../../../g', bases[3], 'fred:///s/g'], // may change to fred:///s//a/../../../g ['../../../../g', bases[3], 'fred:///g'], @@ -1381,7 +1382,7 @@ var relativeTests2 = [ ['../', bases[4], 'http:///s//a/'], ['../g', bases[4], 'http:///s//a/g'], ['../../', bases[4], 'http:///s//'], - ['../../g' , bases[4], 'http:///s//g'], + ['../../g', bases[4], 'http:///s//g'], // may change to http:///s//a/../../g ['../../../g', bases[4], 'http:///s/g'], // may change to http:///s//a/../../../g @@ -1569,10 +1570,10 @@ var throws = [ true, false, 0, - function () {} + function() {} ]; for (var i = 0; i < throws.length; i++) { - assert.throws(function () { url.format(throws[i]); }, TypeError); + assert.throws(function() { url.format(throws[i]); }, TypeError); }; assert(url.format('') === ''); assert(url.format({}) === ''); diff --git a/test/parallel/test-utf8-scripts.js b/test/parallel/test-utf8-scripts.js index b9bef97a5eabfe..3a891283509b9e 100644 --- a/test/parallel/test-utf8-scripts.js +++ b/test/parallel/test-utf8-scripts.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-util-format.js b/test/parallel/test-util-format.js index 715509419806af..6761671e1997bd 100644 --- a/test/parallel/test-util-format.js +++ b/test/parallel/test-util-format.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -57,8 +58,10 @@ assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%'); assert.equal(util.format(new Error('foo')), '[Error: foo]'); function CustomError(msg) { Error.call(this); - Object.defineProperty(this, 'message', { value: msg, enumerable: false }); - Object.defineProperty(this, 'name', { value: 'CustomError', enumerable: false }); + Object.defineProperty(this, 'message', + { value: msg, enumerable: false }); + Object.defineProperty(this, 'name', + { value: 'CustomError', enumerable: false }); } util.inherits(CustomError, Error); assert.equal(util.format(new CustomError('bar')), '[CustomError: bar]'); diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index f4aeced4d98abc..3e51e8485a9b4b 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -92,7 +93,7 @@ var w = { '\\\\': 2, '\\\\\\': 3, '\\\\\\\\': 4, -} +}; var y = ['a', 'b', 'c']; y['\\\\\\'] = 'd'; @@ -112,16 +113,16 @@ function test_color_style(style, input, implicit) { var with_color = util.inspect(input, false, 0, true); var expect = '\u001b[' + color[0] + 'm' + without_color + '\u001b[' + color[1] + 'm'; - assert.equal(with_color, expect, 'util.inspect color for style '+style); + assert.equal(with_color, expect, 'util.inspect color for style ' + style); } -test_color_style('special', function(){}); +test_color_style('special', function() {}); test_color_style('number', 123.456); test_color_style('boolean', true); test_color_style('undefined', undefined); test_color_style('null', null); test_color_style('string', 'test string'); -test_color_style('date', new Date); +test_color_style('date', new Date()); test_color_style('regexp', /regexp/); // an object with "hasOwnProperty" overwritten should not throw @@ -146,10 +147,14 @@ assert(util.inspect(subject, { depth: null }).indexOf('{ d: 0 }') !== -1); // "customInspect" option can enable/disable calling inspect() on objects subject = { inspect: function() { return 123; } }; -assert(util.inspect(subject, { customInspect: true }).indexOf('123') !== -1); -assert(util.inspect(subject, { customInspect: true }).indexOf('inspect') === -1); -assert(util.inspect(subject, { customInspect: false }).indexOf('123') === -1); -assert(util.inspect(subject, { customInspect: false }).indexOf('inspect') !== -1); +assert(util.inspect(subject, + { customInspect: true }).indexOf('123') !== -1); +assert(util.inspect(subject, + { customInspect: true }).indexOf('inspect') === -1); +assert(util.inspect(subject, + { customInspect: false }).indexOf('123') === -1); +assert(util.inspect(subject, + { customInspect: false }).indexOf('inspect') !== -1); // custom inspect() functions should be able to return other Objects subject.inspect = function() { return { foo: 'bar' }; }; @@ -166,7 +171,7 @@ util.inspect(subject, { customInspectOptions: true }); function test_lines(input) { var count_lines = function(str) { return (str.match(/\n/g) || []).length; - } + }; var without_color = util.inspect(input); var with_color = util.inspect(input, {colors: true}); @@ -232,6 +237,75 @@ if (typeof Symbol !== 'undefined') { subject[Symbol('symbol')] = 42; assert.equal(util.inspect(subject), '[ 1, 2, 3 ]'); - assert.equal(util.inspect(subject, options), '[ 1, 2, 3, [length]: 3, [Symbol(symbol)]: 42 ]'); + assert.equal(util.inspect(subject, options), + '[ 1, 2, 3, [length]: 3, [Symbol(symbol)]: 42 ]'); + +} +<<<<<<< HEAD +======= + +// test Set +assert.equal(util.inspect(new Set()), 'Set {}'); +assert.equal(util.inspect(new Set([1, 2, 3])), 'Set { 1, 2, 3 }'); +var set = new Set(['foo']); +set.bar = 42; +assert.equal(util.inspect(set, true), 'Set { \'foo\', [size]: 1, bar: 42 }'); + +// test Map +assert.equal(util.inspect(new Map()), 'Map {}'); +assert.equal(util.inspect(new Map([[1, 'a'], [2, 'b'], [3, 'c']])), + 'Map { 1 => \'a\', 2 => \'b\', 3 => \'c\' }'); +var map = new Map([['foo', null]]); +map.bar = 42; +assert.equal(util.inspect(map, true), + 'Map { \'foo\' => null, [size]: 1, bar: 42 }'); + +// test Promise +assert.equal(util.inspect(Promise.resolve(3)), 'Promise { 3 }'); +assert.equal(util.inspect(Promise.reject(3)), 'Promise { 3 }'); +assert.equal(util.inspect(new Promise(function() {})), 'Promise { }'); +var promise = Promise.resolve('foo'); +promise.bar = 42; +assert.equal(util.inspect(promise), 'Promise { \'foo\', bar: 42 }'); + +// Make sure it doesn't choke on polyfills. Unlike Set/Map, there is no standard +// interface to synchronously inspect a Promise, so our techniques only work on +// a bonafide native Promise. +var oldPromise = Promise; +global.Promise = function() { this.bar = 42; }; +assert.equal(util.inspect(new Promise()), '{ bar: 42 }'); +global.Promise = oldPromise; + + +// Test alignment of items in container +// Assumes that the first numeric character is the start of an item. + +function checkAlignment(container) { + var lines = util.inspect(container).split('\n'); + var pos; + lines.forEach(function(line) { + var npos = line.search(/\d/); + if (npos !== -1) { + if (pos !== undefined) + assert.equal(pos, npos, 'container items not aligned'); + pos = npos; + } + }); +} +var big_array = []; +for (var i = 0; i < 100; i++) { + big_array.push(i); } + +checkAlignment(big_array); +checkAlignment(function() { + var obj = {}; + big_array.forEach(function(v) { + obj[v] = null; + }); + return obj; +}()); +checkAlignment(new Set(big_array)); +checkAlignment(new Map(big_array.map(function(y) { return [y, null]; }))); +>>>>>>> f29762f... test: enable linting for tests diff --git a/test/parallel/test-util-log.js b/test/parallel/test-util-log.js index f157c80bec93dc..fbe3963348adb9 100644 --- a/test/parallel/test-util-log.js +++ b/test/parallel/test-util-log.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var util = require('util'); @@ -17,7 +18,7 @@ var tests = [ {input: null, output: 'null'}, {input: false, output: 'false'}, {input: 42, output: '42'}, - {input: function(){}, output: '[Function]'}, + {input: function() {}, output: '[Function]'}, {input: parseInt('not a number', 10), output: 'NaN'}, {input: {answer: 42}, output: '{ answer: 42 }'}, {input: [1,2,3], output: '[ 1, 2, 3 ]'} diff --git a/test/parallel/test-util.js b/test/parallel/test-util.js index 03456d64393842..2795d3ecd68662 100644 --- a/test/parallel/test-util.js +++ b/test/parallel/test-util.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -13,7 +14,7 @@ assert.equal(true, util.isArray(context('Array')())); assert.equal(false, util.isArray({})); assert.equal(false, util.isArray({ push: function() {} })); assert.equal(false, util.isArray(/regexp/)); -assert.equal(false, util.isArray(new Error)); +assert.equal(false, util.isArray(new Error())); assert.equal(false, util.isArray(Object.create(Array.prototype))); // isRegExp @@ -33,13 +34,13 @@ assert.equal(true, util.isDate(new (context('Date')))); assert.equal(false, util.isDate(Date())); assert.equal(false, util.isDate({})); assert.equal(false, util.isDate([])); -assert.equal(false, util.isDate(new Error)); +assert.equal(false, util.isDate(new Error())); assert.equal(false, util.isDate(Object.create(Date.prototype))); // isError -assert.equal(true, util.isError(new Error)); -assert.equal(true, util.isError(new TypeError)); -assert.equal(true, util.isError(new SyntaxError)); +assert.equal(true, util.isError(new Error())); +assert.equal(true, util.isError(new TypeError())); +assert.equal(true, util.isError(new SyntaxError())); assert.equal(true, util.isError(new (context('Error')))); assert.equal(true, util.isError(new (context('TypeError')))); assert.equal(true, util.isError(new (context('SyntaxError')))); @@ -53,11 +54,11 @@ assert.ok(util.isObject({}) === true); // isPrimitive assert.equal(false, util.isPrimitive({})); -assert.equal(false, util.isPrimitive(new Error)); +assert.equal(false, util.isPrimitive(new Error())); assert.equal(false, util.isPrimitive(new Date())); assert.equal(false, util.isPrimitive([])); assert.equal(false, util.isPrimitive(/regexp/)); -assert.equal(false, util.isPrimitive(function(){})); +assert.equal(false, util.isPrimitive(function() {})); assert.equal(false, util.isPrimitive(new Number(1))); assert.equal(false, util.isPrimitive(new String('bla'))); assert.equal(false, util.isPrimitive(new Boolean(true))); @@ -81,7 +82,7 @@ assert.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); // inherits var ctor = function() {}; -assert.throws(function() { util.inherits(ctor, {}) }, TypeError); -assert.throws(function() { util.inherits(ctor, null) }, TypeError); -assert.throws(function() { util.inherits(null, ctor) }, TypeError); -assert.doesNotThrow(function() { util.inherits(ctor, ctor) }, TypeError); +assert.throws(function() { util.inherits(ctor, {}); }, TypeError); +assert.throws(function() { util.inherits(ctor, null); }, TypeError); +assert.throws(function() { util.inherits(null, ctor); }, TypeError); +assert.doesNotThrow(function() { util.inherits(ctor, ctor); }, TypeError); diff --git a/test/parallel/test-v8-flag-type-check.js b/test/parallel/test-v8-flag-type-check.js new file mode 100644 index 00000000000000..68bf30dba3cdbc --- /dev/null +++ b/test/parallel/test-v8-flag-type-check.js @@ -0,0 +1,7 @@ +'use strict'; +var common = require('../common'); +var assert = require('assert'); +var v8 = require('v8'); + +assert.throws(function() {v8.setFlagsFromString(1);}, TypeError); +assert.throws(function() {v8.setFlagsFromString();}, TypeError); diff --git a/test/parallel/test-v8-flags.js b/test/parallel/test-v8-flags.js index 886583e4c51229..d21cbc6c2635a5 100644 --- a/test/parallel/test-v8-flags.js +++ b/test/parallel/test-v8-flags.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var v8 = require('v8'); @@ -8,5 +9,5 @@ assert(eval('%_IsSmi(42)')); assert(vm.runInThisContext('%_IsSmi(42)')); v8.setFlagsFromString('--noallow_natives_syntax'); -assert.throws(function() { eval('%_IsSmi(42)') }, SyntaxError); -assert.throws(function() { vm.runInThisContext('%_IsSmi(42)') }, SyntaxError); +assert.throws(function() { eval('%_IsSmi(42)'); }, SyntaxError); +assert.throws(function() { vm.runInThisContext('%_IsSmi(42)'); }, SyntaxError); diff --git a/test/parallel/test-v8-stats.js b/test/parallel/test-v8-stats.js index 7acb9db1e04306..e48c1d70365073 100644 --- a/test/parallel/test-v8-stats.js +++ b/test/parallel/test-v8-stats.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var v8 = require('v8'); diff --git a/test/parallel/test-vm-basic.js b/test/parallel/test-vm-basic.js index 092aa1a6363904..96c615c44af10c 100644 --- a/test/parallel/test-vm-basic.js +++ b/test/parallel/test-vm-basic.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-context-async-script.js b/test/parallel/test-vm-context-async-script.js index 979fc24a1671b4..e146d48343aa60 100644 --- a/test/parallel/test-vm-context-async-script.js +++ b/test/parallel/test-vm-context-async-script.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); @@ -7,7 +8,7 @@ var sandbox = { setTimeout: setTimeout }; var ctx = vm.createContext(sandbox); vm.runInContext('setTimeout(function() { x = 3; }, 0);', ctx); -setTimeout(function () { +setTimeout(function() { assert.strictEqual(sandbox.x, 3); assert.strictEqual(ctx.x, 3); }, 1); diff --git a/test/parallel/test-vm-context-property-forwarding.js b/test/parallel/test-vm-context-property-forwarding.js index b1012f5dee05a5..5fcd64b8ba9094 100644 --- a/test/parallel/test-vm-context-property-forwarding.js +++ b/test/parallel/test-vm-context-property-forwarding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-context.js b/test/parallel/test-vm-context.js index cdf76529efc08b..45e19e6638892e 100644 --- a/test/parallel/test-vm-context.js +++ b/test/parallel/test-vm-context.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -22,7 +23,7 @@ assert.equal(3, context.foo); assert.equal('lala', context.thing); // Issue GH-227: -assert.throws(function () { +assert.throws(function() { vm.runInNewContext('', null, 'some.js'); }, TypeError); diff --git a/test/parallel/test-vm-create-and-run-in-context.js b/test/parallel/test-vm-create-and-run-in-context.js index cf6a4875d5aa64..01df6ad4531e4a 100644 --- a/test/parallel/test-vm-create-and-run-in-context.js +++ b/test/parallel/test-vm-create-and-run-in-context.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-vm-create-context-accessors.js b/test/parallel/test-vm-create-context-accessors.js index 23fc935389def8..678cf3fbd2128e 100644 --- a/test/parallel/test-vm-create-context-accessors.js +++ b/test/parallel/test-vm-create-context-accessors.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-create-context-arg.js b/test/parallel/test-vm-create-context-arg.js index 65dcf05e2b2bf3..d44eeec18decd5 100644 --- a/test/parallel/test-vm-create-context-arg.js +++ b/test/parallel/test-vm-create-context-arg.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); @@ -12,7 +13,7 @@ assert.doesNotThrow(function() { }); assert.doesNotThrow(function() { - var sandbox = {}; - vm.createContext(sandbox); - vm.createContext(sandbox); + var sandbox = {}; + vm.createContext(sandbox); + vm.createContext(sandbox); }); diff --git a/test/parallel/test-vm-create-context-circular-reference.js b/test/parallel/test-vm-create-context-circular-reference.js index ae23eba167b9fb..cb6a90dcaef321 100644 --- a/test/parallel/test-vm-create-context-circular-reference.js +++ b/test/parallel/test-vm-create-context-circular-reference.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-cross-context.js b/test/parallel/test-vm-cross-context.js index 56c6040be7f5d6..20a3792b28578e 100644 --- a/test/parallel/test-vm-cross-context.js +++ b/test/parallel/test-vm-cross-context.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -5,5 +6,5 @@ var vm = require('vm'); var ctx = vm.createContext(global); assert.doesNotThrow(function() { - vm.runInContext("!function() { var x = console.log; }()", ctx); + vm.runInContext('!function() { var x = console.log; }()', ctx); }); diff --git a/test/parallel/test-vm-debug-context.js b/test/parallel/test-vm-debug-context.js index 2c6919423d230e..72851f16040d4a 100644 --- a/test/parallel/test-vm-debug-context.js +++ b/test/parallel/test-vm-debug-context.js @@ -1,3 +1,5 @@ +/* eslint-disable no-debugger */ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-function-declaration.js b/test/parallel/test-vm-function-declaration.js index c9a4fbb03eb620..5ff194e12dd8d8 100644 --- a/test/parallel/test-vm-function-declaration.js +++ b/test/parallel/test-vm-function-declaration.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -13,7 +14,7 @@ code += 'function b(){}\n'; // Grab the global b function as the completion value, to ensure that // we are getting the global function, and not some other thing -code += '(function(){return this})().b;\n' +code += '(function(){return this})().b;\n'; var res = vm.runInContext(code, o, 'test'); diff --git a/test/parallel/test-vm-global-define-property.js b/test/parallel/test-vm-global-define-property.js index ea30a4f3156745..f7f3e4f3df7d76 100644 --- a/test/parallel/test-vm-global-define-property.js +++ b/test/parallel/test-vm-global-define-property.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-vm-global-identity.js b/test/parallel/test-vm-global-identity.js index bc3d9653a7c437..647edb22b44db0 100644 --- a/test/parallel/test-vm-global-identity.js +++ b/test/parallel/test-vm-global-identity.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-harmony-proxies.js b/test/parallel/test-vm-harmony-proxies.js index 859d77cd62d73b..2f008615ebaf54 100644 --- a/test/parallel/test-vm-harmony-proxies.js +++ b/test/parallel/test-vm-harmony-proxies.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --harmony_proxies var common = require('../common'); diff --git a/test/parallel/test-vm-harmony-symbols.js b/test/parallel/test-vm-harmony-symbols.js index 127e3c4a2b291e..86fde1b978ffb2 100644 --- a/test/parallel/test-vm-harmony-symbols.js +++ b/test/parallel/test-vm-harmony-symbols.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-is-context.js b/test/parallel/test-vm-is-context.js index 7b3d6616ee4a1d..5a46a452b91634 100644 --- a/test/parallel/test-vm-is-context.js +++ b/test/parallel/test-vm-is-context.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-new-script-new-context.js b/test/parallel/test-vm-new-script-new-context.js index 742f247a11c19a..4619c9345c5e5c 100644 --- a/test/parallel/test-vm-new-script-new-context.js +++ b/test/parallel/test-vm-new-script-new-context.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); var Script = require('vm').Script; @@ -23,7 +24,7 @@ assert.throws(function() { console.error('undefined reference'); var error; script = new Script('foo.bar = 5;'); -assert.throws(function () { +assert.throws(function() { script.runInNewContext(); }, /not defined/); @@ -48,7 +49,7 @@ assert.equal(2, foo); console.error('call a function by reference'); script = new Script('f()'); -function changeFoo() { foo = 100 } +function changeFoo() { foo = 100; } script.runInNewContext({ f: changeFoo }); assert.equal(foo, 100); diff --git a/test/parallel/test-vm-new-script-this-context.js b/test/parallel/test-vm-new-script-this-context.js index 99d40bea2e2237..16d8acd1ca6700 100644 --- a/test/parallel/test-vm-new-script-this-context.js +++ b/test/parallel/test-vm-new-script-this-context.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); var Script = require('vm').Script; @@ -34,7 +35,7 @@ assert.equal(2, bar); assert.equal(1, foo); console.error('call a function'); -f = function() { foo = 100 }; +f = function() { foo = 100; }; script = new Script('f()'); script.runInThisContext(script); assert.equal(100, foo); diff --git a/test/parallel/test-vm-run-in-new-context.js b/test/parallel/test-vm-run-in-new-context.js index 4772c3b99d9eb5..da14a041face31 100644 --- a/test/parallel/test-vm-run-in-new-context.js +++ b/test/parallel/test-vm-run-in-new-context.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ // Flags: --expose-gc var common = require('../common'); @@ -34,7 +35,7 @@ assert.equal(2, obj.bar); assert.equal(2, foo); console.error('call a function by reference'); -function changeFoo() { foo = 100 } +function changeFoo() { foo = 100; } vm.runInNewContext('f()', { f: changeFoo }); assert.equal(foo, 100); @@ -44,7 +45,7 @@ vm.runInNewContext('f.a = 2', { f: f }); assert.equal(f.a, 2); console.error('use function in context without referencing context'); -var fn = vm.runInNewContext('(function() { obj.p = {}; })', { obj: {} }) +var fn = vm.runInNewContext('(function() { obj.p = {}; })', { obj: {} }); gc(); fn(); // Should not crash diff --git a/test/parallel/test-vm-static-this.js b/test/parallel/test-vm-static-this.js index b7b013396bef8a..fb9cb764f8422c 100644 --- a/test/parallel/test-vm-static-this.js +++ b/test/parallel/test-vm-static-this.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); var vm = require('vm'); @@ -30,6 +31,6 @@ assert.equal(2, bar); assert.equal(1, foo); console.error('call a function'); -f = function() { foo = 100 }; +f = function() { foo = 100; }; vm.runInThisContext('f()'); assert.equal(100, foo); diff --git a/test/parallel/test-vm-timeout.js b/test/parallel/test-vm-timeout.js index 9925e03ad69d30..e9511e59230a84 100644 --- a/test/parallel/test-vm-timeout.js +++ b/test/parallel/test-vm-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-writedouble.js b/test/parallel/test-writedouble.js index 24ceb885f54318..2a9ab11107f147 100644 --- a/test/parallel/test-writedouble.js +++ b/test/parallel/test-writedouble.js @@ -1,3 +1,4 @@ +'use strict'; /* * Tests to verify we're writing doubles correctly */ diff --git a/test/parallel/test-writefloat.js b/test/parallel/test-writefloat.js index 5d5be20354377f..948bf4910208a5 100644 --- a/test/parallel/test-writefloat.js +++ b/test/parallel/test-writefloat.js @@ -1,3 +1,4 @@ +'use strict'; /* * Tests to verify we're writing floats correctly */ diff --git a/test/parallel/test-writeint.js b/test/parallel/test-writeint.js index 064716ad0ccd16..ee981a157ad761 100644 --- a/test/parallel/test-writeint.js +++ b/test/parallel/test-writeint.js @@ -1,3 +1,4 @@ +'use strict'; /* * Tests to verify we're writing signed integers correctly */ diff --git a/test/parallel/test-writeuint.js b/test/parallel/test-writeuint.js index ec2efa12fb95ef..22579ceecaef2d 100644 --- a/test/parallel/test-writeuint.js +++ b/test/parallel/test-writeuint.js @@ -1,3 +1,4 @@ +'use strict'; /* * A battery of tests to help us read a series of uints */ diff --git a/test/parallel/test-zlib-close-after-write.js b/test/parallel/test-zlib-close-after-write.js index cbb1ac1fe1f26a..c02ff33fb5eb63 100644 --- a/test/parallel/test-zlib-close-after-write.js +++ b/test/parallel/test-zlib-close-after-write.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/parallel/test-zlib-const.js b/test/parallel/test-zlib-const.js index df9ca3d50097ad..511eca613a5229 100644 --- a/test/parallel/test-zlib-const.js +++ b/test/parallel/test-zlib-const.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-zlib-convenience-methods.js b/test/parallel/test-zlib-convenience-methods.js index a32d5d1d4c3f18..5808bdf04a8f14 100644 --- a/test/parallel/test-zlib-convenience-methods.js +++ b/test/parallel/test-zlib-convenience-methods.js @@ -1,3 +1,4 @@ +'use strict'; // test convenience methods with and without options supplied var common = require('../common'); diff --git a/test/parallel/test-zlib-dictionary-fail.js b/test/parallel/test-zlib-dictionary-fail.js index ea50bf40982d6d..ced829f8d49963 100644 --- a/test/parallel/test-zlib-dictionary-fail.js +++ b/test/parallel/test-zlib-dictionary-fail.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/parallel/test-zlib-dictionary.js b/test/parallel/test-zlib-dictionary.js index 3a159e6090126e..109f4273f767d0 100644 --- a/test/parallel/test-zlib-dictionary.js +++ b/test/parallel/test-zlib-dictionary.js @@ -1,3 +1,4 @@ +'use strict'; // test compression/decompression with dictionary var common = require('../common'); diff --git a/test/parallel/test-zlib-flush.js b/test/parallel/test-zlib-flush.js index cfebda7bd2e5fa..6281b8eb21feb2 100644 --- a/test/parallel/test-zlib-flush.js +++ b/test/parallel/test-zlib-flush.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/parallel/test-zlib-from-gzip.js b/test/parallel/test-zlib-from-gzip.js index b218b4edfcae69..6076a6f09ba00b 100644 --- a/test/parallel/test-zlib-from-gzip.js +++ b/test/parallel/test-zlib-from-gzip.js @@ -1,3 +1,4 @@ +'use strict'; // test unzipping a file that was created with a non-node gzip lib, // piped in as fast as possible. diff --git a/test/parallel/test-zlib-from-string.js b/test/parallel/test-zlib-from-string.js index 4ce77a8b528136..49f4d139c148d9 100644 --- a/test/parallel/test-zlib-from-string.js +++ b/test/parallel/test-zlib-from-string.js @@ -1,3 +1,4 @@ +'use strict'; // test compressing and uncompressing a string with zlib var common = require('../common'); diff --git a/test/parallel/test-zlib-invalid-input.js b/test/parallel/test-zlib-invalid-input.js index 948ea2244808b2..e1e81bacc1a499 100644 --- a/test/parallel/test-zlib-invalid-input.js +++ b/test/parallel/test-zlib-invalid-input.js @@ -1,3 +1,4 @@ +'use strict'; // test uncompressing invalid input var common = require('../common'), @@ -24,15 +25,15 @@ var unzips = [ zlib.Unzip(), zlib.Inflate(), zlib.InflateRaw() ]; var hadError = []; -unzips.forEach(function (uz, i) { - console.error('Error for '+uz.constructor.name); +unzips.forEach(function(uz, i) { + console.error('Error for ' + uz.constructor.name); uz.on('error', function(er) { console.error('Error event', er); hadError[i] = true; }); uz.on('end', function(er) { - throw new Error('end event should not be emitted '+uz.constructor.name); + throw new Error('end event should not be emitted ' + uz.constructor.name); }); // this will trigger error event diff --git a/test/parallel/test-zlib-params.js b/test/parallel/test-zlib-params.js index 6f1920956159f3..f349c8dbd0afec 100644 --- a/test/parallel/test-zlib-params.js +++ b/test/parallel/test-zlib-params.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/parallel/test-zlib-random-byte-pipes.js b/test/parallel/test-zlib-random-byte-pipes.js index 4044cbd211a857..fcdc81443cac91 100644 --- a/test/parallel/test-zlib-random-byte-pipes.js +++ b/test/parallel/test-zlib-random-byte-pipes.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-zlib-write-after-close.js b/test/parallel/test-zlib-write-after-close.js index 54b316631f739d..a1d9adb6d9b996 100644 --- a/test/parallel/test-zlib-write-after-close.js +++ b/test/parallel/test-zlib-write-after-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/parallel/test-zlib-write-after-flush.js b/test/parallel/test-zlib-write-after-flush.js index c0dbee7774b42d..4c53ca49ebf758 100644 --- a/test/parallel/test-zlib-write-after-flush.js +++ b/test/parallel/test-zlib-write-after-flush.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/parallel/test-zlib-zero-byte.js b/test/parallel/test-zlib-zero-byte.js index e7c8ddc954f77a..9aa260a7f3149d 100644 --- a/test/parallel/test-zlib-zero-byte.js +++ b/test/parallel/test-zlib-zero-byte.js @@ -1,8 +1,9 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); -var gz = zlib.Gzip() +var gz = zlib.Gzip(); var emptyBuffer = new Buffer(0); var received = 0; gz.on('data', function(c) { diff --git a/test/parallel/test-zlib.js b/test/parallel/test-zlib.js index bb9ba53d5df2cc..aaa965c424ed98 100644 --- a/test/parallel/test-zlib.js +++ b/test/parallel/test-zlib.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/pummel/test-abort-fatal-error.js b/test/pummel/test-abort-fatal-error.js index 045ff6da7f69e0..9f012c9dfb14b8 100644 --- a/test/pummel/test-abort-fatal-error.js +++ b/test/pummel/test-abort-fatal-error.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/pummel/test-buffer-big.js b/test/pummel/test-buffer-big.js index 9caa9287663a19..b36b992214ffc5 100644 --- a/test/pummel/test-buffer-big.js +++ b/test/pummel/test-buffer-big.js @@ -1,8 +1,9 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); // The tests below should throw an error, not abort the process... -assert.throws(function() { new Buffer(0x3fffffff + 1) }, RangeError); -assert.throws(function() { new Int8Array(0x3fffffff + 1) }, RangeError); -assert.throws(function() { new ArrayBuffer(0x3fffffff + 1) }, RangeError); -assert.throws(function() { new Float64Array(0x7ffffff + 1) }, RangeError); +assert.throws(function() { new Buffer(0x3fffffff + 1); }, RangeError); +assert.throws(function() { new Int8Array(0x3fffffff + 1); }, RangeError); +assert.throws(function() { new ArrayBuffer(0x3fffffff + 1); }, RangeError); +assert.throws(function() { new Float64Array(0x7ffffff + 1); }, RangeError); diff --git a/test/pummel/test-child-process-spawn-loop.js b/test/pummel/test-child-process-spawn-loop.js index a6129dd0bb2081..defed7d5f613d2 100644 --- a/test/pummel/test-child-process-spawn-loop.js +++ b/test/pummel/test-child-process-spawn-loop.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-crypto-dh.js b/test/pummel/test-crypto-dh.js index 0f3a5407dc7ed5..5588cdb7089b5b 100644 --- a/test/pummel/test-crypto-dh.js +++ b/test/pummel/test-crypto-dh.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -19,21 +20,22 @@ assert.throws(function() { }); var hashes = { - modp1 : "b4b330a6ffeacfbd861e7fe2135b4431", - modp2 : "7c3c5cad8b9f378d88f1dd64a4b6413a", - modp5 : "b1d2acc22c542e08669a5c5ae812694d", - modp14 : "8d041538cecc1a7d915ba4b718f8ad20", - modp15 : "dc3b93def24e078c4fbf92d5e14ba69b", - modp16 : "a273487f46f699461f613b3878d9dfd9", - modp17 : "dc76e09935310348c492de9bd82014d0", - modp18 : "db08973bfd2371758a69db180871c993" -} + modp1 : 'b4b330a6ffeacfbd861e7fe2135b4431', + modp2 : '7c3c5cad8b9f378d88f1dd64a4b6413a', + modp5 : 'b1d2acc22c542e08669a5c5ae812694d', + modp14 : '8d041538cecc1a7d915ba4b718f8ad20', + modp15 : 'dc3b93def24e078c4fbf92d5e14ba69b', + modp16 : 'a273487f46f699461f613b3878d9dfd9', + modp17 : 'dc76e09935310348c492de9bd82014d0', + modp18 : 'db08973bfd2371758a69db180871c993' +}; for (var name in hashes) { var group = crypto.getDiffieHellman(name); var private_key = group.getPrime('hex'); var hash1 = hashes[name]; - var hash2 = crypto.createHash('md5').update(private_key.toUpperCase()).digest('hex'); + var hash2 = crypto.createHash('md5') + .update(private_key.toUpperCase()).digest('hex'); assert.equal(hash1, hash2); assert.equal(group.getGenerator('hex'), '02'); } diff --git a/test/pummel/test-dh-regr.js b/test/pummel/test-dh-regr.js index 5c40173b121040..a6270bd2419cb0 100644 --- a/test/pummel/test-dh-regr.js +++ b/test/pummel/test-dh-regr.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-dtrace-jsstack.js b/test/pummel/test-dtrace-jsstack.js index e86a497f6967ba..831402fc87c780 100644 --- a/test/pummel/test-dtrace-jsstack.js +++ b/test/pummel/test-dtrace-jsstack.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var os = require('os'); @@ -14,18 +15,18 @@ if (os.type() != 'SunOS') { var frames = [ 'stalloogle', 'bagnoogle', 'doogle' ]; var expected; -var stalloogle = function (str) { +var stalloogle = function(str) { expected = str; os.loadavg(); }; -var bagnoogle = function (arg0, arg1) { +var bagnoogle = function(arg0, arg1) { stalloogle(arg0 + ' is ' + arg1 + ' except that it is read-only'); }; var done = false; -var doogle = function () { +var doogle = function() { if (!done) setTimeout(doogle, 10); @@ -46,15 +47,15 @@ var dtrace = spawn('dtrace', [ '-qwn', 'syscall::getloadavg:entry/pid == ' + var output = ''; -dtrace.stderr.on('data', function (data) { +dtrace.stderr.on('data', function(data) { console.log('dtrace: ' + data); }); -dtrace.stdout.on('data', function (data) { +dtrace.stdout.on('data', function(data) { output += data; }); -dtrace.on('exit', function (code) { +dtrace.on('exit', function(code) { if (code != 0) { console.error('dtrace exited with code ' + code); process.exit(code); diff --git a/test/pummel/test-exec.js b/test/pummel/test-exec.js index bbedc3a5729515..41d81426e63e6f 100644 --- a/test/pummel/test-exec.js +++ b/test/pummel/test-exec.js @@ -1,14 +1,15 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; if (process.platform !== 'win32') { // Unix. - var SLEEP3_COMMAND = "sleep 3"; + var SLEEP3_COMMAND = 'sleep 3'; } else { // Windows: `choice` is a command built into cmd.exe. Use another cmd process // to create a process tree, so we can catch bugs related to it. - var SLEEP3_COMMAND = "cmd /c choice /t 3 /c X /d X"; + var SLEEP3_COMMAND = 'cmd /c choice /t 3 /c X /d X'; } diff --git a/test/pummel/test-fs-readfile-large.js b/test/pummel/test-fs-readfile-large.js index d8c6634fb827ab..b6afbc254d317c 100644 --- a/test/pummel/test-fs-readfile-large.js +++ b/test/pummel/test-fs-readfile-large.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -26,7 +27,7 @@ function makeFile(done) { } } -makeFile(function () { +makeFile(function() { fs.readFile(filename, function(err) { assert.ok(err, 'should get RangeError'); assert.equal(err.name, 'RangeError', 'should get RangeError'); @@ -34,6 +35,6 @@ makeFile(function () { }); }); -process.on('uncaughtException', function (err) { +process.on('uncaughtException', function(err) { assert.ok(!err, 'should not throw uncaughtException'); }); diff --git a/test/pummel/test-fs-watch-file-slow.js b/test/pummel/test-fs-watch-file-slow.js index df8763a4e2839d..cd4b16bf310b99 100644 --- a/test/pummel/test-fs-watch-file-slow.js +++ b/test/pummel/test-fs-watch-file-slow.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -42,13 +43,13 @@ setTimeout(createFile, TIMEOUT); function createFile() { console.log('creating file'); - fs.writeFileSync(FILENAME, "test"); + fs.writeFileSync(FILENAME, 'test'); setTimeout(touchFile, TIMEOUT); } function touchFile() { console.log('touch file'); - fs.writeFileSync(FILENAME, "test"); + fs.writeFileSync(FILENAME, 'test'); setTimeout(removeFile, TIMEOUT); } diff --git a/test/pummel/test-fs-watch-file.js b/test/pummel/test-fs-watch-file.js index 199bf5242e251b..7b57803dd4ec93 100644 --- a/test/pummel/test-fs-watch-file.js +++ b/test/pummel/test-fs-watch-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -123,7 +124,7 @@ assert.doesNotThrow( function a(curr, prev) { ++watchSeenFour; assert.equal(1, watchSeenFour); - fs.unwatchFile("." + path.sep + filenameFour, a); + fs.unwatchFile('.' + path.sep + filenameFour, a); } fs.watchFile(filenameFour, a); } diff --git a/test/pummel/test-fs-watch-non-recursive.js b/test/pummel/test-fs-watch-non-recursive.js index 60d2c6b6a84900..6adb193928e44f 100644 --- a/test/pummel/test-fs-watch-non-recursive.js +++ b/test/pummel/test-fs-watch-non-recursive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -14,7 +15,7 @@ function cleanup() { process.on('exit', cleanup); cleanup(); -try { fs.mkdirSync(testsubdir, 0700); } catch (e) {} +try { fs.mkdirSync(testsubdir, 0o700); } catch (e) {} // Need a grace period, else the mkdirSync() above fires off an event. setTimeout(function() { diff --git a/test/pummel/test-http-client-reconnect-bug.js b/test/pummel/test-http-client-reconnect-bug.js index 00a38608125dbd..bd852e45f19410 100644 --- a/test/pummel/test-http-client-reconnect-bug.js +++ b/test/pummel/test-http-client-reconnect-bug.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-http-many-keep-alive-connections.js b/test/pummel/test-http-many-keep-alive-connections.js index fdd7a068102c3d..d90d4d97531095 100644 --- a/test/pummel/test-http-many-keep-alive-connections.js +++ b/test/pummel/test-http-many-keep-alive-connections.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/pummel/test-http-upload-timeout.js b/test/pummel/test-http-upload-timeout.js index f889c60f177b5f..08132e3c7594d1 100644 --- a/test/pummel/test-http-upload-timeout.js +++ b/test/pummel/test-http-upload-timeout.js @@ -1,3 +1,4 @@ +'use strict'; // This tests setTimeout() by having multiple clients connecting and sending // data in random intervals. Clients are also randomly disconnecting until there // are no more clients left. If no false timeout occurs, this test has passed. diff --git a/test/pummel/test-https-ci-reneg-attack.js b/test/pummel/test-https-ci-reneg-attack.js index 1ca965e99ec583..fa38bea0011131 100644 --- a/test/pummel/test-https-ci-reneg-attack.js +++ b/test/pummel/test-https-ci-reneg-attack.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/pummel/test-https-large-response.js b/test/pummel/test-https-large-response.js index 5ad5da480ca7a4..1aa36464a158e4 100644 --- a/test/pummel/test-https-large-response.js +++ b/test/pummel/test-https-large-response.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-https-no-reader.js b/test/pummel/test-https-no-reader.js index 798a4f70b64f81..8f407e2d7d48f8 100644 --- a/test/pummel/test-https-no-reader.js +++ b/test/pummel/test-https-no-reader.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-keep-alive.js b/test/pummel/test-keep-alive.js index 58af58a25353a6..d03cb1d74f3683 100644 --- a/test/pummel/test-keep-alive.js +++ b/test/pummel/test-keep-alive.js @@ -1,3 +1,4 @@ +'use strict'; if (process.platform === 'win32') { console.log('skipping this test because there is no wrk on windows'); process.exit(0); @@ -37,7 +38,8 @@ function runAb(opts, callback) { args.push('Connection: close'); } - args.push(url.format({ hostname: '127.0.0.1', port: common.PORT, protocol: 'http'})); + args.push(url.format({ hostname: '127.0.0.1', + port: common.PORT, protocol: 'http'})); //console.log(comm, args.join(' ')); diff --git a/test/pummel/test-net-connect-econnrefused.js b/test/pummel/test-net-connect-econnrefused.js index be3db49aa4fe7a..113b04e31f3ae1 100644 --- a/test/pummel/test-net-connect-econnrefused.js +++ b/test/pummel/test-net-connect-econnrefused.js @@ -1,3 +1,4 @@ +'use strict'; // verify that connect reqs are properly cleaned up var common = require('../common'); diff --git a/test/pummel/test-net-connect-memleak.js b/test/pummel/test-net-connect-memleak.js index 66b7e926d8cadc..855bf1f070d7c8 100644 --- a/test/pummel/test-net-connect-memleak.js +++ b/test/pummel/test-net-connect-memleak.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --expose-gc var common = require('../common'); diff --git a/test/pummel/test-net-many-clients.js b/test/pummel/test-net-many-clients.js index fce7f33e669ccb..b70efbda582571 100644 --- a/test/pummel/test-net-many-clients.js +++ b/test/pummel/test-net-many-clients.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/pummel/test-net-pause.js b/test/pummel/test-net-pause.js index 26eec2cfd092d6..6386d29835da11 100644 --- a/test/pummel/test-net-pause.js +++ b/test/pummel/test-net-pause.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/pummel/test-net-pingpong-delay.js b/test/pummel/test-net-pingpong-delay.js index 8a30e7bae7f5fd..e459c71a7185ac 100644 --- a/test/pummel/test-net-pingpong-delay.js +++ b/test/pummel/test-net-pingpong-delay.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/pummel/test-net-pingpong.js b/test/pummel/test-net-pingpong.js index d38064e64a4067..a7ede0b0565ac9 100644 --- a/test/pummel/test-net-pingpong.js +++ b/test/pummel/test-net-pingpong.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/pummel/test-net-throttle.js b/test/pummel/test-net-throttle.js index 45c0a6fb6d9cc5..d556d8aaa86c43 100644 --- a/test/pummel/test-net-throttle.js +++ b/test/pummel/test-net-throttle.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -20,7 +21,8 @@ var server = net.createServer(function(connection) { connection.write(body.slice(part_N, 2 * part_N)); assert.equal(false, connection.write(body.slice(2 * part_N, N))); console.log('bufferSize: ' + connection.bufferSize, 'expecting', N); - assert.ok(0 <= connection.bufferSize && connection._writableState.length <= N); + assert.ok(0 <= connection.bufferSize && + connection._writableState.length <= N); connection.end(); }); diff --git a/test/pummel/test-net-timeout.js b/test/pummel/test-net-timeout.js index 47214fc98f528a..347e3a4344d37b 100644 --- a/test/pummel/test-net-timeout.js +++ b/test/pummel/test-net-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -12,7 +13,7 @@ var echo_server = net.createServer(function(socket) { socket.on('timeout', function() { console.log('server timeout'); - timeouttime = new Date; + timeouttime = new Date(); console.dir(timeouttime); socket.destroy(); }); @@ -53,7 +54,7 @@ echo_server.listen(common.PORT, function() { if (exchanges == 5) { console.log('wait for timeout - should come in ' + timeout + ' ms'); - starttime = new Date; + starttime = new Date(); console.dir(starttime); } } diff --git a/test/pummel/test-net-timeout2.js b/test/pummel/test-net-timeout2.js index 2eb97a6e7e2f1c..c7b445f96c4e38 100644 --- a/test/pummel/test-net-timeout2.js +++ b/test/pummel/test-net-timeout2.js @@ -1,3 +1,4 @@ +'use strict'; // socket.write was not resetting the timeout timer. See // https://github.com/joyent/node/issues/2002 diff --git a/test/pummel/test-net-write-callbacks.js b/test/pummel/test-net-write-callbacks.js index b43729d0c1ed46..21eae0f5ab72d0 100644 --- a/test/pummel/test-net-write-callbacks.js +++ b/test/pummel/test-net-write-callbacks.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/pummel/test-next-tick-infinite-calls.js b/test/pummel/test-next-tick-infinite-calls.js index 5177135a34a6e2..d4fdb3496423eb 100644 --- a/test/pummel/test-next-tick-infinite-calls.js +++ b/test/pummel/test-next-tick-infinite-calls.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-process-hrtime.js b/test/pummel/test-process-hrtime.js index faf97d8a8daed1..4fd66c03907aac 100644 --- a/test/pummel/test-process-hrtime.js +++ b/test/pummel/test-process-hrtime.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-process-uptime.js b/test/pummel/test-process-uptime.js index b105edebbd8689..a80806c2099cb1 100644 --- a/test/pummel/test-process-uptime.js +++ b/test/pummel/test-process-uptime.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-regress-GH-814.js b/test/pummel/test-regress-GH-814.js index 20183960e04af8..0059af1037a80b 100644 --- a/test/pummel/test-regress-GH-814.js +++ b/test/pummel/test-regress-GH-814.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --expose_gc function newBuffer(size, value) { diff --git a/test/pummel/test-regress-GH-814_2.js b/test/pummel/test-regress-GH-814_2.js index 7443e4f57eaf98..6dd2f2d32e5646 100644 --- a/test/pummel/test-regress-GH-814_2.js +++ b/test/pummel/test-regress-GH-814_2.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --expose_gc var common = require('../common'); diff --git a/test/pummel/test-regress-GH-892.js b/test/pummel/test-regress-GH-892.js index af314349ffd962..d84170d7648a10 100644 --- a/test/pummel/test-regress-GH-892.js +++ b/test/pummel/test-regress-GH-892.js @@ -1,3 +1,4 @@ +'use strict'; // Uploading a big file via HTTPS causes node to drop out of the event loop. // https://github.com/joyent/node/issues/892 // In this test we set up an HTTPS in this process and launch a subprocess diff --git a/test/pummel/test-smalloc-alloc-segfault.js b/test/pummel/test-smalloc-alloc-segfault.js index 3e89f726ce7f70..d41ccaee09b79d 100644 --- a/test/pummel/test-smalloc-alloc-segfault.js +++ b/test/pummel/test-smalloc-alloc-segfault.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-smalloc-dispose-segfault.js b/test/pummel/test-smalloc-dispose-segfault.js index e94d9d5ba17c76..9364cca344c136 100644 --- a/test/pummel/test-smalloc-dispose-segfault.js +++ b/test/pummel/test-smalloc-dispose-segfault.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-smalloc-sliceonto-segfault.js b/test/pummel/test-smalloc-sliceonto-segfault.js index ed43828a530ee6..e9e00979ff2814 100644 --- a/test/pummel/test-smalloc-sliceonto-segfault.js +++ b/test/pummel/test-smalloc-sliceonto-segfault.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-stream-pipe-multi.js b/test/pummel/test-stream-pipe-multi.js index 00d17f17425c0b..807e3c1415154e 100644 --- a/test/pummel/test-stream-pipe-multi.js +++ b/test/pummel/test-stream-pipe-multi.js @@ -1,3 +1,4 @@ +'use strict'; // Test that having a bunch of streams piping in parallel // doesn't break anything. diff --git a/test/pummel/test-stream2-basic.js b/test/pummel/test-stream2-basic.js index 543acd61c11d67..c83d80c5029e70 100644 --- a/test/pummel/test-stream2-basic.js +++ b/test/pummel/test-stream2-basic.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var R = require('_stream_readable'); var assert = require('assert'); @@ -88,7 +89,7 @@ function run() { same: assert.deepEqual, ok: assert, equal: assert.equal, - end: function () { + end: function() { count--; run(); } @@ -96,7 +97,7 @@ function run() { } // ensure all tests have run -process.on("exit", function () { +process.on('exit', function() { assert.equal(count, 0); }); @@ -153,9 +154,9 @@ test('pipe', function(t) { 'xxxxx', 'xxxxx', 'xxxxx', - 'xxxxx' ] + 'xxxxx' ]; - var w = new TestWriter; + var w = new TestWriter(); var flush = true; w.on('end', function(received) { @@ -168,7 +169,7 @@ test('pipe', function(t) { -[1,2,3,4,5,6,7,8,9].forEach(function(SPLIT) { +[1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(function(SPLIT) { test('unpipe', function(t) { var r = new TestReader(5); @@ -226,7 +227,7 @@ test('pipe', function(t) { // both writers should get the same exact data. test('multipipe', function(t) { var r = new TestReader(5); - var w = [ new TestWriter, new TestWriter ]; + var w = [ new TestWriter(), new TestWriter() ]; var expect = [ 'xxxxx', 'xxxxx', @@ -254,7 +255,7 @@ test('multipipe', function(t) { }); -[1,2,3,4,5,6,7,8,9].forEach(function(SPLIT) { +[1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(function(SPLIT) { test('multi-unpipe', function(t) { var r = new TestReader(5); @@ -301,90 +302,90 @@ test('multipipe', function(t) { }); }); -test('back pressure respected', function (t) { +test('back pressure respected', function(t) { function noop() {} var r = new R({ objectMode: true }); r._read = noop; var counter = 0; - r.push(["one"]); - r.push(["two"]); - r.push(["three"]); - r.push(["four"]); + r.push(['one']); + r.push(['two']); + r.push(['three']); + r.push(['four']); r.push(null); var w1 = new R(); - w1.write = function (chunk) { + w1.write = function(chunk) { console.error('w1.emit("close")'); - assert.equal(chunk[0], "one"); - w1.emit("close"); - process.nextTick(function () { + assert.equal(chunk[0], 'one'); + w1.emit('close'); + process.nextTick(function() { r.pipe(w2); r.pipe(w3); - }) + }); }; w1.end = noop; r.pipe(w1); - var expected = ["two", "two", "three", "three", "four", "four"]; + var expected = ['two', 'two', 'three', 'three', 'four', 'four']; var w2 = new R(); - w2.write = function (chunk) { + w2.write = function(chunk) { console.error('w2 write', chunk, counter); assert.equal(chunk[0], expected.shift()); assert.equal(counter, 0); counter++; - if (chunk[0] === "four") { + if (chunk[0] === 'four') { return true; } - setTimeout(function () { + setTimeout(function() { counter--; - console.error("w2 drain"); - w2.emit("drain"); + console.error('w2 drain'); + w2.emit('drain'); }, 10); return false; - } + }; w2.end = noop; var w3 = new R(); - w3.write = function (chunk) { + w3.write = function(chunk) { console.error('w3 write', chunk, counter); assert.equal(chunk[0], expected.shift()); assert.equal(counter, 1); counter++; - if (chunk[0] === "four") { + if (chunk[0] === 'four') { return true; } - setTimeout(function () { + setTimeout(function() { counter--; - console.error("w3 drain"); - w3.emit("drain"); + console.error('w3 drain'); + w3.emit('drain'); }, 50); return false; }; - w3.end = function () { + w3.end = function() { assert.equal(counter, 2); assert.equal(expected.length, 0); t.end(); }; }); -test('read(0) for ended streams', function (t) { +test('read(0) for ended streams', function(t) { var r = new R(); var written = false; var ended = false; - r._read = function (n) {}; + r._read = function(n) {}; - r.push(new Buffer("foo")); + r.push(new Buffer('foo')); r.push(null); var v = r.read(0); @@ -393,38 +394,38 @@ test('read(0) for ended streams', function (t) { var w = new R(); - w.write = function (buffer) { + w.write = function(buffer) { written = true; assert.equal(ended, false); - assert.equal(buffer.toString(), "foo") + assert.equal(buffer.toString(), 'foo'); }; - w.end = function () { + w.end = function() { ended = true; assert.equal(written, true); t.end(); }; r.pipe(w); -}) +}); -test('sync _read ending', function (t) { +test('sync _read ending', function(t) { var r = new R(); var called = false; - r._read = function (n) { + r._read = function(n) { r.push(null); }; - r.once('end', function () { + r.once('end', function() { called = true; - }) + }); r.read(); - process.nextTick(function () { + process.nextTick(function() { assert.equal(called, true); t.end(); - }) + }); }); test('adding readable triggers data flow', function(t) { diff --git a/test/pummel/test-timer-wrap.js b/test/pummel/test-timer-wrap.js index fdfb855a75830d..62ba69d3fde033 100644 --- a/test/pummel/test-timer-wrap.js +++ b/test/pummel/test-timer-wrap.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-timer-wrap2.js b/test/pummel/test-timer-wrap2.js index 8a7502888b5557..b289a85644a068 100644 --- a/test/pummel/test-timer-wrap2.js +++ b/test/pummel/test-timer-wrap2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-timers.js b/test/pummel/test-timers.js index f676b98438852e..2225da91edcf5f 100644 --- a/test/pummel/test-timers.js +++ b/test/pummel/test-timers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -11,9 +12,9 @@ clearTimeout(null); clearInterval(null); assert.equal(true, setTimeout instanceof Function); -var starttime = new Date; +var starttime = new Date(); setTimeout(function() { - var endtime = new Date; + var endtime = new Date(); var diff = endtime - starttime; assert.ok(diff > 0); @@ -29,7 +30,7 @@ clearTimeout(id); setInterval(function() { interval_count += 1; - var endtime = new Date; + var endtime = new Date( ); var diff = endtime - starttime; assert.ok(diff > 0); diff --git a/test/pummel/test-tls-ci-reneg-attack.js b/test/pummel/test-tls-ci-reneg-attack.js index 22c48699d080a7..49b9a87a7dbdc3 100644 --- a/test/pummel/test-tls-ci-reneg-attack.js +++ b/test/pummel/test-tls-ci-reneg-attack.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/pummel/test-tls-connect-memleak.js b/test/pummel/test-tls-connect-memleak.js index 53275da60ed2a9..0345f9a6f62886 100644 --- a/test/pummel/test-tls-connect-memleak.js +++ b/test/pummel/test-tls-connect-memleak.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --expose-gc var common = require('../common'); diff --git a/test/pummel/test-tls-securepair-client.js b/test/pummel/test-tls-securepair-client.js index cbff5feac8fb39..7542ce62bcd154 100644 --- a/test/pummel/test-tls-securepair-client.js +++ b/test/pummel/test-tls-securepair-client.js @@ -1,3 +1,4 @@ +'use strict'; // var common = require('../common'); diff --git a/test/pummel/test-tls-server-large-request.js b/test/pummel/test-tls-server-large-request.js index c5eebb01a16fdb..e6ef89c72eb659 100644 --- a/test/pummel/test-tls-server-large-request.js +++ b/test/pummel/test-tls-server-large-request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-tls-session-timeout.js b/test/pummel/test-tls-session-timeout.js index 74a1abc99052cb..962b1206b6c956 100644 --- a/test/pummel/test-tls-session-timeout.js +++ b/test/pummel/test-tls-session-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.opensslCli) { @@ -46,7 +47,7 @@ function doTest() { // file containing a proper serialization of a session ticket. // To avoid a source control diff, we copy the ticket to a temporary file. - var sessionFileName = (function () { + var sessionFileName = (function() { var ticketFileName = 'tls-session-ticket.txt'; var fixturesPath = join(common.fixturesDir, ticketFileName); var tmpPath = join(common.tmpDir, ticketFileName); @@ -56,7 +57,7 @@ function doTest() { // Expects a callback -- cb(connectionType : enum ['New'|'Reused']) - var Client = function (cb) { + var Client = function(cb) { var flags = [ 's_client', '-connect', 'localhost:' + common.PORT, @@ -73,7 +74,7 @@ function doTest() { }); client.on('exit', function(code) { var connectionType; - var grepConnectionType = function (line) { + var grepConnectionType = function(line) { var matches = line.match(/(New|Reused), /); if (matches) { connectionType = matches[1]; @@ -101,7 +102,7 @@ function doTest() { assert(connectionType === 'New'); Client(function(connectionType) { assert(connectionType === 'Reused'); - setTimeout(function () { + setTimeout(function() { Client(function(connectionType) { assert(connectionType === 'New'); server.close(); diff --git a/test/pummel/test-tls-throttle.js b/test/pummel/test-tls-throttle.js index a8a83a2a3a9001..3eb1af6da75818 100644 --- a/test/pummel/test-tls-throttle.js +++ b/test/pummel/test-tls-throttle.js @@ -1,3 +1,4 @@ +'use strict'; // Server sends a large string. Client counts bytes and pauses every few // seconds. Makes sure that pause and resume work properly. diff --git a/test/pummel/test-vm-memleak.js b/test/pummel/test-vm-memleak.js index 916b65d6da49a9..f93f34127f9219 100644 --- a/test/pummel/test-vm-memleak.js +++ b/test/pummel/test-vm-memleak.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --max_old_space_size=32 var assert = require('assert'); diff --git a/test/pummel/test-watch-file.js b/test/pummel/test-watch-file.js index 3e92efc26c9edb..1d0ef77d543e43 100644 --- a/test/pummel/test-watch-file.js +++ b/test/pummel/test-watch-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-chdir.js b/test/sequential/test-chdir.js index a24753de2d28e0..0fab45cb0c2803 100644 --- a/test/sequential/test-chdir.js +++ b/test/sequential/test-chdir.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -20,4 +21,5 @@ fs.rmdirSync(dir); assert.throws(function() { process.chdir({}); }, TypeError, 'Bad argument.'); assert.throws(function() { process.chdir(); }, TypeError, 'Bad argument.'); -assert.throws(function() { process.chdir("x", "y"); }, TypeError, 'Bad argument.'); +assert.throws(function() { process.chdir('x', 'y'); }, + TypeError, 'Bad argument.'); diff --git a/test/sequential/test-child-process-emfile.js b/test/sequential/test-child-process-emfile.js index 66be12749c9f03..964b63a2b4513d 100644 --- a/test/sequential/test-child-process-emfile.js +++ b/test/sequential/test-child-process-emfile.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index 5cd9ee433d6d35..13982e00a6756d 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -58,7 +59,8 @@ assert.deepEqual(ret, msgBuf); ret = execFileSync(process.execPath, args, { encoding: 'utf8' }); -assert.strictEqual(ret, msg + '\n', 'execFileSync encoding result should match'); +assert.strictEqual(ret, msg + '\n', + 'execFileSync encoding result should match'); // Verify that the cwd option works - GH #7824 (function() { diff --git a/test/sequential/test-child-process-fork-getconnections.js b/test/sequential/test-child-process-fork-getconnections.js index 6848b2ffa0b9c6..a587713b6132f2 100644 --- a/test/sequential/test-child-process-fork-getconnections.js +++ b/test/sequential/test-child-process-fork-getconnections.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; diff --git a/test/sequential/test-cluster-listening-port.js b/test/sequential/test-cluster-listening-port.js index 5d68b066cfd9e2..eb8a974d04bbf8 100644 --- a/test/sequential/test-cluster-listening-port.js +++ b/test/sequential/test-cluster-listening-port.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var cluster = require('cluster'); var net = require('net'); diff --git a/test/sequential/test-debug-args.js b/test/sequential/test-debug-args.js index 7aaef76a641fd6..eb1533d4418a55 100644 --- a/test/sequential/test-debug-args.js +++ b/test/sequential/test-debug-args.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --debugger var common = require('../common'); diff --git a/test/sequential/test-deprecation-flags.js b/test/sequential/test-deprecation-flags.js index 2af60a17364999..e8565a33635744 100644 --- a/test/sequential/test-deprecation-flags.js +++ b/test/sequential/test-deprecation-flags.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var execFile = require('child_process').execFile; @@ -12,7 +13,8 @@ execFile(node, normal, function(er, stdout, stderr) { console.error('normal: show deprecation warning'); assert.equal(er, null); assert.equal(stdout, ''); - assert.equal(stderr, 'util.p: Use console.error() instead\n\'This is deprecated\'\n'); + assert.equal(stderr, + 'util.p: Use console.error() instead\n\'This is deprecated\'\n'); console.log('normal ok'); }); diff --git a/test/sequential/test-force-repl.js b/test/sequential/test-force-repl.js index c0ad1484ff25cc..5907dc2019a3a3 100644 --- a/test/sequential/test-force-repl.js +++ b/test/sequential/test-force-repl.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/sequential/test-fs-watch-recursive.js b/test/sequential/test-fs-watch-recursive.js index a789dcb3061b3d..f77b86e436985b 100644 --- a/test/sequential/test-fs-watch-recursive.js +++ b/test/sequential/test-fs-watch-recursive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -23,7 +24,7 @@ if (process.platform === 'darwin') { try { fs.rmdirSync(testsubdir); } catch (e) { } }; - try { fs.mkdirSync(testsubdir, 0700); } catch (e) {} + try { fs.mkdirSync(testsubdir, 0o700); } catch (e) {} assert.doesNotThrow(function() { var watcher = fs.watch(testDir, {recursive: true}); diff --git a/test/sequential/test-fs-watch.js b/test/sequential/test-fs-watch.js index d92a10cd808a10..1cfaad9b3ec975 100644 --- a/test/sequential/test-fs-watch.js +++ b/test/sequential/test-fs-watch.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -41,7 +42,7 @@ fs.writeFileSync(filepathOne, 'hello'); assert.doesNotThrow( function() { - var watcher = fs.watch(filepathOne) + var watcher = fs.watch(filepathOne); watcher.on('change', function(event, filename) { assert.equal('change', event); @@ -82,7 +83,7 @@ setTimeout(function() { }, 20); try { fs.unlinkSync(filepathThree); } catch (e) {} -try { fs.mkdirSync(testsubdir, 0700); } catch (e) {} +try { fs.mkdirSync(testsubdir, 0o700); } catch (e) {} assert.doesNotThrow( function() { @@ -123,7 +124,7 @@ assert.throws(function() { oldhandle.close(); // clean up assert.throws(function() { - var w = fs.watchFile(__filename, {persistent:false}, function(){}); + var w = fs.watchFile(__filename, {persistent:false}, function() {}); oldhandle = w._handle; w._handle = { stop: w._handle.stop }; w.stop(); diff --git a/test/sequential/test-http-pipeline-flood.js b/test/sequential/test-http-pipeline-flood.js index 6eeb785f9cbc2a..cb9fc97a865b70 100644 --- a/test/sequential/test-http-pipeline-flood.js +++ b/test/sequential/test-http-pipeline-flood.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-init.js b/test/sequential/test-init.js index abc6378a637e93..f68c001f64fffa 100644 --- a/test/sequential/test-init.js +++ b/test/sequential/test-init.js @@ -1,3 +1,4 @@ +'use strict'; (function() { var assert = require('assert'), child = require('child_process'), diff --git a/test/sequential/test-memory-usage-emfile.js b/test/sequential/test-memory-usage-emfile.js index e95fe429c37645..e4f85488f40d42 100644 --- a/test/sequential/test-memory-usage-emfile.js +++ b/test/sequential/test-memory-usage-emfile.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-mkdir-rmdir.js b/test/sequential/test-mkdir-rmdir.js index 63dc78df381e78..7bd156419e8a94 100644 --- a/test/sequential/test-mkdir-rmdir.js +++ b/test/sequential/test-mkdir-rmdir.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -9,12 +10,12 @@ var d = path.join(common.tmpDir, 'dir'); var mkdir_error = false; var rmdir_error = false; -fs.mkdir(d, 0666, function(err) { +fs.mkdir(d, 0o666, function(err) { if (err) { console.log('mkdir error: ' + err.message); mkdir_error = true; } else { - fs.mkdir(d, 0666, function(err) { + fs.mkdir(d, 0o666, function(err) { console.log('expect EEXIST error: ', err); assert.ok(err.message.match(/^EEXIST/), 'got EEXIST message'); assert.equal(err.code, 'EEXIST', 'got EEXIST code'); diff --git a/test/sequential/test-module-loading.js b/test/sequential/test-module-loading.js index c1d8df4553370c..dfca2e420263b6 100644 --- a/test/sequential/test-module-loading.js +++ b/test/sequential/test-module-loading.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -53,7 +54,7 @@ assert.equal('D', d3.D()); assert.equal(true, common.indirectInstanceOf(d4.D, Function)); assert.equal('D', d4.D()); -assert.ok((new a.SomeClass) instanceof c.SomeClass); +assert.ok((new a.SomeClass()) instanceof c.SomeClass); common.debug('test index.js modules ids and relative loading'); var one = require('../fixtures/nested-index/one'), @@ -89,7 +90,7 @@ common.debug('test name clashes'); var my_path = require('../fixtures/path'); assert.ok(common.indirectInstanceOf(my_path.path_func, Function)); // this one does not exist and should throw -assert.throws(function() { require('./utils')}); +assert.throws(function() { require('./utils'); }); var errorThrown = false; try { @@ -187,7 +188,7 @@ assert.deepEqual(json, { // the appropriate children, and so on. var children = module.children.reduce(function red(set, child) { - var id = path.relative(path.dirname(__dirname), child.id) + var id = path.relative(path.dirname(__dirname), child.id); id = id.replace(/\\/g, '/'); set[id] = child.children.reduce(red, {}); return set; diff --git a/test/sequential/test-net-GH-5504.js b/test/sequential/test-net-GH-5504.js index 2ee0a1d86d7af3..0478de55d62592 100644 --- a/test/sequential/test-net-GH-5504.js +++ b/test/sequential/test-net-GH-5504.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-net-listen-exclusive-random-ports.js b/test/sequential/test-net-listen-exclusive-random-ports.js index 2922a2b06e140f..c32273a59b2a50 100644 --- a/test/sequential/test-net-listen-exclusive-random-ports.js +++ b/test/sequential/test-net-listen-exclusive-random-ports.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/sequential/test-net-localport.js b/test/sequential/test-net-localport.js index 239196813ad8a3..09b6627c79ce47 100644 --- a/test/sequential/test-net-localport.js +++ b/test/sequential/test-net-localport.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -17,4 +18,4 @@ var server = net.createServer(function(socket) { }).on('connect', function() { assert.strictEqual(client.localPort, common.PORT + 1); }); -}) +}); diff --git a/test/sequential/test-net-server-address.js b/test/sequential/test-net-server-address.js index 717d46f1bbb059..1e91c348ef02ca 100644 --- a/test/sequential/test-net-server-address.js +++ b/test/sequential/test-net-server-address.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -60,12 +61,12 @@ server1.listen(common.PORT, function() { // Test without hostname or port var server2 = net.createServer(); -server2.on('error', function (e) { +server2.on('error', function(e) { console.log('Error on ip socket: ' + e.toString()); }); // Don't specify the port number -server2.listen(function () { +server2.listen(function() { var address = server2.address(); assert.strictEqual(address.address, anycast_ipv6); assert.strictEqual(address.family, family_ipv6); @@ -75,12 +76,12 @@ server2.listen(function () { // Test without hostname, but with a false-y port var server3 = net.createServer(); -server3.on('error', function (e) { +server3.on('error', function(e) { console.log('Error on ip socket: ' + e.toString()); }); // Specify a false-y port number -server3.listen(0, function () { +server3.listen(0, function() { var address = server3.address(); assert.strictEqual(address.address, anycast_ipv6); assert.strictEqual(address.family, family_ipv6); @@ -90,12 +91,12 @@ server3.listen(0, function () { // Test without hostname, but with port -1 var server4 = net.createServer(); -server4.on('error', function (e) { +server4.on('error', function(e) { console.log('Error on ip socket: ' + e.toString()); }); // Specify -1 as port number -server4.listen(-1, function () { +server4.listen(-1, function() { var address = server4.address(); assert.strictEqual(address.address, anycast_ipv6); assert.strictEqual(address.family, family_ipv6); diff --git a/test/sequential/test-net-server-bind.js b/test/sequential/test-net-server-bind.js index 3a7cd0e15b21db..c77341418c2c6d 100644 --- a/test/sequential/test-net-server-bind.js +++ b/test/sequential/test-net-server-bind.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/sequential/test-next-tick-error-spin.js b/test/sequential/test-next-tick-error-spin.js index a150ea7a589f63..7a76ab1e12df68 100644 --- a/test/sequential/test-next-tick-error-spin.js +++ b/test/sequential/test-next-tick-error-spin.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -22,24 +23,24 @@ if (process.argv[2] !== 'child') { // in the error handler, we trigger several MakeCallback events d.on('error', function(e) { - console.log('a') - console.log('b') - console.log('c') - console.log('d') - console.log('e') + console.log('a'); + console.log('b'); + console.log('c'); + console.log('d'); + console.log('e'); f(); }); function f() { process.nextTick(function() { d.run(function() { - throw(new Error('x')); + throw new Error('x'); }); }); } f(); - setTimeout(function () { + setTimeout(function() { console.error('broke in!'); //process.stdout.close(); //process.stderr.close(); diff --git a/test/sequential/test-pipe-address.js b/test/sequential/test-pipe-address.js index 6497eb7f1246c1..b9e544e97458b4 100644 --- a/test/sequential/test-pipe-address.js +++ b/test/sequential/test-pipe-address.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/sequential/test-pipe-head.js b/test/sequential/test-pipe-head.js index 4fa3eaa4daa59c..ac8b16515158eb 100644 --- a/test/sequential/test-pipe-head.js +++ b/test/sequential/test-pipe-head.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-pipe-stream.js b/test/sequential/test-pipe-stream.js index 5e5837b29843b6..ba4005e9e02fe0 100644 --- a/test/sequential/test-pipe-stream.js +++ b/test/sequential/test-pipe-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/sequential/test-pipe-unref.js b/test/sequential/test-pipe-unref.js index 53853b9bdcba66..4580f2a66ee4d6 100644 --- a/test/sequential/test-pipe-unref.js +++ b/test/sequential/test-pipe-unref.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-pipe.js b/test/sequential/test-pipe.js index 11ea83b88422ba..2ef19c37ea8ca4 100644 --- a/test/sequential/test-pipe.js +++ b/test/sequential/test-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/sequential/test-pump-file2tcp-noexist.js b/test/sequential/test-pump-file2tcp-noexist.js index 8b2057e533c60e..1ffdb5d4615ce3 100644 --- a/test/sequential/test-pump-file2tcp-noexist.js +++ b/test/sequential/test-pump-file2tcp-noexist.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/sequential/test-pump-file2tcp.js b/test/sequential/test-pump-file2tcp.js index 50b576771f9074..86effb7c6c9a28 100644 --- a/test/sequential/test-pump-file2tcp.js +++ b/test/sequential/test-pump-file2tcp.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/sequential/test-readdir.js b/test/sequential/test-readdir.js index bba28d0d7a8bfc..4987dc1848035d 100644 --- a/test/sequential/test-readdir.js +++ b/test/sequential/test-readdir.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/sequential/test-regress-GH-1531.js b/test/sequential/test-regress-GH-1531.js index 9e1b8e3077870e..0d06cc3485218a 100644 --- a/test/sequential/test-regress-GH-1531.js +++ b/test/sequential/test-regress-GH-1531.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-regress-GH-1697.js b/test/sequential/test-regress-GH-1697.js index 18d1829174dd8b..ff5754f357dfc1 100644 --- a/test/sequential/test-regress-GH-1697.js +++ b/test/sequential/test-regress-GH-1697.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'), cp = require('child_process'), @@ -39,7 +40,7 @@ if (process.argv[2] === 'server') { // Block the event loop for 1 second var start = (new Date()).getTime(); - while ((new Date).getTime() < start + 1000) {} + while ((new Date()).getTime() < start + 1000) {} client.write(alittle); diff --git a/test/sequential/test-regress-GH-1726.js b/test/sequential/test-regress-GH-1726.js index 74578ab4e0fe55..859ab6cc5e4253 100644 --- a/test/sequential/test-regress-GH-1726.js +++ b/test/sequential/test-regress-GH-1726.js @@ -1,3 +1,4 @@ +'use strict'; // Open a chain of five Node processes each a child of the next. The final // process exits immediately. Each process in the chain is instructed to // exit when its child exits. @@ -26,7 +27,7 @@ assert.ok(!child.stderr); console.error('gen=%d, pid=%d', gen, process.pid); /* -var timer = setTimeout(function () { +var timer = setTimeout(function() { throw new Error('timeout! gen='+gen); }, 1000); */ diff --git a/test/sequential/test-regress-GH-1899.js b/test/sequential/test-regress-GH-1899.js index 8663eb5a4dd1ea..98396aae13b8f9 100644 --- a/test/sequential/test-regress-GH-1899.js +++ b/test/sequential/test-regress-GH-1899.js @@ -1,3 +1,4 @@ +'use strict'; var path = require('path'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/sequential/test-regress-GH-3542.js b/test/sequential/test-regress-GH-3542.js index 32b3433318855b..80f2a4c9c3e4a2 100644 --- a/test/sequential/test-regress-GH-3542.js +++ b/test/sequential/test-regress-GH-3542.js @@ -1,3 +1,4 @@ +'use strict'; // This test is only relevant on Windows. if (process.platform !== 'win32') { return process.exit(0); @@ -22,8 +23,8 @@ function test(p) { test('//localhost/c$/windows/system32'); test('//localhost/c$/windows'); -test('//localhost/c$/') -test('\\\\localhost\\c$') +test('//localhost/c$/'); +test('\\\\localhost\\c$'); test('c:\\'); test('c:'); test(process.env.windir); diff --git a/test/sequential/test-regress-GH-3739.js b/test/sequential/test-regress-GH-3739.js index d08cfce60226ba..cc16b22dc44c46 100644 --- a/test/sequential/test-regress-GH-3739.js +++ b/test/sequential/test-regress-GH-3739.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), fs = require('fs'), diff --git a/test/sequential/test-regress-GH-4015.js b/test/sequential/test-regress-GH-4015.js index 38a77c82086b1c..7f0e03f9ac08e1 100644 --- a/test/sequential/test-regress-GH-4015.js +++ b/test/sequential/test-regress-GH-4015.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; diff --git a/test/sequential/test-regress-GH-4027.js b/test/sequential/test-regress-GH-4027.js index de2dff180db5c0..da91be95b849a8 100644 --- a/test/sequential/test-regress-GH-4027.js +++ b/test/sequential/test-regress-GH-4027.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/sequential/test-regress-GH-4948.js b/test/sequential/test-regress-GH-4948.js index e78870b704c917..c87ade9850ccf4 100644 --- a/test/sequential/test-regress-GH-4948.js +++ b/test/sequential/test-regress-GH-4948.js @@ -1,10 +1,11 @@ +'use strict'; // https://github.com/joyent/node/issues/4948 var common = require('../common'); var http = require('http'); var reqCount = 0; -var server = http.createServer(function(serverReq, serverRes){ +var server = http.createServer(function(serverReq, serverRes) { if (reqCount) { serverRes.end(); server.close(); @@ -15,9 +16,10 @@ var server = http.createServer(function(serverReq, serverRes){ // normally the use case would be to call an external site // does not require connecting locally or to itself to fail - var r = http.request({hostname: 'localhost', port: common.PORT}, function(res) { + var r = http.request({hostname: 'localhost', + port: common.PORT}, function(res) { // required, just needs to be in the client response somewhere - serverRes.end(); + serverRes.end(); // required for test to fail res.on('data', function(data) { }); diff --git a/test/sequential/test-regress-GH-746.js b/test/sequential/test-regress-GH-746.js index 93346c43f1d9e2..4b79f3c4e355d1 100644 --- a/test/sequential/test-regress-GH-746.js +++ b/test/sequential/test-regress-GH-746.js @@ -1,3 +1,4 @@ +'use strict'; // Just test that destroying stdin doesn't mess up listening on a server. // This is a regression test for GH-746. diff --git a/test/sequential/test-regress-GH-784.js b/test/sequential/test-regress-GH-784.js index a33b6f23c479bf..08f660add31048 100644 --- a/test/sequential/test-regress-GH-784.js +++ b/test/sequential/test-regress-GH-784.js @@ -1,3 +1,4 @@ +'use strict'; // Regression test for GH-784 // https://github.com/joyent/node/issues/784 // diff --git a/test/sequential/test-regress-GH-819.js b/test/sequential/test-regress-GH-819.js index 16d0f3bc54e4f3..e459587d97cba9 100644 --- a/test/sequential/test-regress-GH-819.js +++ b/test/sequential/test-regress-GH-819.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/sequential/test-regress-GH-877.js b/test/sequential/test-regress-GH-877.js index 80c8456742d5af..69671b9dc4a143 100644 --- a/test/sequential/test-regress-GH-877.js +++ b/test/sequential/test-regress-GH-877.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'); var assert = require('assert'); diff --git a/test/sequential/test-require-cache-without-stat.js b/test/sequential/test-require-cache-without-stat.js index 701d47bfc91800..c602ab82b11f4d 100644 --- a/test/sequential/test-require-cache-without-stat.js +++ b/test/sequential/test-require-cache-without-stat.js @@ -1,3 +1,4 @@ +'use strict'; // We've experienced a regression where the module loader stats a bunch of // directories on require() even if it's been called before. The require() // should caching the request. diff --git a/test/sequential/test-setproctitle.js b/test/sequential/test-setproctitle.js index b7e6dd8b552a5d..a0b15e2b85d8c3 100644 --- a/test/sequential/test-setproctitle.js +++ b/test/sequential/test-setproctitle.js @@ -1,3 +1,4 @@ +'use strict'; // Original test written by Jakub Lekstan // FIXME add sunos support diff --git a/test/sequential/test-sigint-infinite-loop.js b/test/sequential/test-sigint-infinite-loop.js index c444caf419188e..8211aeb69ec5db 100644 --- a/test/sequential/test-sigint-infinite-loop.js +++ b/test/sequential/test-sigint-infinite-loop.js @@ -1,3 +1,4 @@ +'use strict'; // This test is to assert that we can SIGINT a script which loops forever. // Ref(http): // groups.google.com/group/nodejs-dev/browse_thread/thread/e20f2f8df0296d3f diff --git a/test/sequential/test-socket-write-after-fin-error.js b/test/sequential/test-socket-write-after-fin-error.js index 5274d6e3dabe43..226440ec502670 100644 --- a/test/sequential/test-socket-write-after-fin-error.js +++ b/test/sequential/test-socket-write-after-fin-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -24,7 +25,7 @@ var server = net.createServer(function(sock) { serverData += c; }); sock.on('end', function() { - gotServerEnd = true + gotServerEnd = true; sock.write(serverData); sock.end(); }); diff --git a/test/sequential/test-socket-write-after-fin.js b/test/sequential/test-socket-write-after-fin.js index 44d98ba512e1ca..ea8ac27b597ec4 100644 --- a/test/sequential/test-socket-write-after-fin.js +++ b/test/sequential/test-socket-write-after-fin.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -12,7 +13,7 @@ var server = net.createServer({ allowHalfOpen: true }, function(sock) { serverData += c; }); sock.on('end', function() { - gotServerEnd = true + gotServerEnd = true; sock.end(serverData); server.close(); }); diff --git a/test/sequential/test-stdin-child-proc.js b/test/sequential/test-stdin-child-proc.js index 4d3ead73ceac6c..93bf265b8b0020 100644 --- a/test/sequential/test-stdin-child-proc.js +++ b/test/sequential/test-stdin-child-proc.js @@ -1,3 +1,4 @@ +'use strict'; // This tests that pausing and resuming stdin does not hang and timeout // when done in a child process. See test/simple/test-stdin-pause-resume.js var common = require('../common'); diff --git a/test/sequential/test-stdin-from-file.js b/test/sequential/test-stdin-from-file.js index bde2a8559c3db3..35aa5b1a89ac38 100644 --- a/test/sequential/test-stdin-from-file.js +++ b/test/sequential/test-stdin-from-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var join = require('path').join; diff --git a/test/sequential/test-stdin-pipe-resume.js b/test/sequential/test-stdin-pipe-resume.js index a326e380a73654..dbac78d78c5e12 100644 --- a/test/sequential/test-stdin-pipe-resume.js +++ b/test/sequential/test-stdin-pipe-resume.js @@ -1,3 +1,4 @@ +'use strict'; // This tests that piping stdin will cause it to resume() as well. var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-stdin-script-child.js b/test/sequential/test-stdin-script-child.js index dcccff1ff5d47c..8590df02d8efe9 100644 --- a/test/sequential/test-stdin-script-child.js +++ b/test/sequential/test-stdin-script-child.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-stdout-cannot-be-closed-child-process-pipe.js b/test/sequential/test-stdout-cannot-be-closed-child-process-pipe.js index 519dce059b2f25..c6f5aecd40e262 100644 --- a/test/sequential/test-stdout-cannot-be-closed-child-process-pipe.js +++ b/test/sequential/test-stdout-cannot-be-closed-child-process-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-stdout-close-catch.js b/test/sequential/test-stdout-close-catch.js index c1165350aec0ba..f0ecf9a7c4b725 100644 --- a/test/sequential/test-stdout-close-catch.js +++ b/test/sequential/test-stdout-close-catch.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/sequential/test-stdout-stderr-reading.js b/test/sequential/test-stdout-stderr-reading.js index 3fe0db0ce3abbd..82fd51cedda1de 100644 --- a/test/sequential/test-stdout-stderr-reading.js +++ b/test/sequential/test-stdout-stderr-reading.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-stdout-to-file.js b/test/sequential/test-stdout-to-file.js index 8a9d0476911c76..4ef473e57ada08 100644 --- a/test/sequential/test-stdout-to-file.js +++ b/test/sequential/test-stdout-to-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/sequential/test-stream2-fs.js b/test/sequential/test-stream2-fs.js index 552d686af02314..96ab97174b2478 100644 --- a/test/sequential/test-stream2-fs.js +++ b/test/sequential/test-stream2-fs.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var R = require('_stream_readable'); var assert = require('assert'); @@ -32,7 +33,7 @@ TestWriter.prototype.write = function(c) { TestWriter.prototype.end = function(c) { if (c) this.buffer.push(c.toString()); this.emit('results', this.buffer); -} +}; var r = new FSReadable(file); var w = new TestWriter(); @@ -41,7 +42,7 @@ w.on('results', function(res) { console.error(res, w.length); assert.equal(w.length, size); var l = 0; - assert.deepEqual(res.map(function (c) { + assert.deepEqual(res.map(function(c) { return c.length; }), expectLengths); console.log('ok'); diff --git a/test/sequential/test-stream2-httpclient-response-end.js b/test/sequential/test-stream2-httpclient-response-end.js index 627960888a7fac..15d7fba27f63af 100644 --- a/test/sequential/test-stream2-httpclient-response-end.js +++ b/test/sequential/test-stream2-httpclient-response-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/sequential/test-stream2-stderr-sync.js b/test/sequential/test-stream2-stderr-sync.js index 9b634116db7fa8..ccbdc55e4feaf9 100644 --- a/test/sequential/test-stream2-stderr-sync.js +++ b/test/sequential/test-stream2-stderr-sync.js @@ -1,3 +1,4 @@ +'use strict'; // Make sure that sync writes to stderr get processed before exiting. var common = require('../common'); diff --git a/test/sequential/test-sync-fileread.js b/test/sequential/test-sync-fileread.js index 3f5f6debd55fea..24a80d96c2601b 100644 --- a/test/sequential/test-sync-fileread.js +++ b/test/sequential/test-sync-fileread.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/sequential/test-tcp-wrap-connect.js b/test/sequential/test-tcp-wrap-connect.js index 2dc9f0cb93a185..9373906c6f612a 100644 --- a/test/sequential/test-tcp-wrap-connect.js +++ b/test/sequential/test-tcp-wrap-connect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var TCP = process.binding('tcp_wrap').TCP; diff --git a/test/sequential/test-tcp-wrap-listen.js b/test/sequential/test-tcp-wrap-listen.js index 2c0856bd951788..a2c07a7a9ce2a2 100644 --- a/test/sequential/test-tcp-wrap-listen.js +++ b/test/sequential/test-tcp-wrap-listen.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-tls-honorcipherorder.js b/test/sequential/test-tls-honorcipherorder.js index cad1a83a30e856..c33cd9eea63465 100644 --- a/test/sequential/test-tls-honorcipherorder.js +++ b/test/sequential/test-tls-honorcipherorder.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-util-debug.js b/test/sequential/test-util-debug.js index 1af9a7705a104a..834c21ec0e50b4 100644 --- a/test/sequential/test-util-debug.js +++ b/test/sequential/test-util-debug.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-vm-syntax-error-stderr.js b/test/sequential/test-vm-syntax-error-stderr.js index b3f76e5e30c5e2..f7b1bef9e309dc 100644 --- a/test/sequential/test-vm-syntax-error-stderr.js +++ b/test/sequential/test-vm-syntax-error-stderr.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/sequential/test-vm-timeout-rethrow.js b/test/sequential/test-vm-timeout-rethrow.js index 547ed2f8d6205b..4f3af900ee0ae2 100644 --- a/test/sequential/test-vm-timeout-rethrow.js +++ b/test/sequential/test-vm-timeout-rethrow.js @@ -1,10 +1,11 @@ +'use strict'; var assert = require('assert'); var vm = require('vm'); var spawn = require('child_process').spawn; if (process.argv[2] === 'child') { var code = 'var j = 0;\n' + - 'for (var i = 0; i < 1000000; i++) j += add(i, i + 1);\n' + 'for (var i = 0; i < 1000000; i++) j += add(i, i + 1);\n' + 'j;'; var ctx = vm.createContext({ diff --git a/test/sequential/test-zerolengthbufferbug.js b/test/sequential/test-zerolengthbufferbug.js index dde08c63914b38..de36444180b1ec 100644 --- a/test/sequential/test-zerolengthbufferbug.js +++ b/test/sequential/test-zerolengthbufferbug.js @@ -1,3 +1,4 @@ +'use strict'; // Serving up a zero-length buffer should work. var common = require('../common'); diff --git a/test/timers/test-timers-reliability.js b/test/timers/test-timers-reliability.js index c240a44685ac50..b4332468bc2ec3 100644 --- a/test/timers/test-timers-reliability.js +++ b/test/timers/test-timers-reliability.js @@ -1,3 +1,4 @@ +'use strict'; // FaketimeFlags: --exclude-monotonic -f '2014-07-21 09:00:00' var common = require('../common'); @@ -31,23 +32,23 @@ var intervalFired = false; */ var monoTimer = new Timer(); -monoTimer.ontimeout = function () { +monoTimer.ontimeout = function() { /* * Make sure that setTimeout's and setInterval's callbacks have * already fired, otherwise it means that they are vulnerable to * time drifting or inconsistent time changes. */ - assert(timerFired); - assert(intervalFired); + assert(timerFired); + assert(intervalFired); }; monoTimer.start(300, 0); -var timer = setTimeout(function () { - timerFired = true; +var timer = setTimeout(function() { + timerFired = true; }, 200); -var interval = setInterval(function () { - intervalFired = true; - clearInterval(interval); +var interval = setInterval(function() { + intervalFired = true; + clearInterval(interval); }, 200); diff --git a/tools/closure_linter/AUTHORS b/tools/closure_linter/AUTHORS deleted file mode 100644 index 2f72bd6b2fce9a..00000000000000 --- a/tools/closure_linter/AUTHORS +++ /dev/null @@ -1,6 +0,0 @@ -# This is a list of contributors to the Closure Linter. - -# Names should be added to this file like so: -# Name or Organization - -Google Inc. diff --git a/tools/closure_linter/LICENSE b/tools/closure_linter/LICENSE deleted file mode 100644 index d9a10c0d8e868e..00000000000000 --- a/tools/closure_linter/LICENSE +++ /dev/null @@ -1,176 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS diff --git a/tools/closure_linter/README b/tools/closure_linter/README deleted file mode 100644 index 4a21b2defc39ea..00000000000000 --- a/tools/closure_linter/README +++ /dev/null @@ -1,9 +0,0 @@ -This repository contains the Closure Linter - a style checker for JavaScript. - -To install the application, run - python ./setup.py install - -After installing, you get two helper applications installed into /usr/local/bin: - - gjslint.py - runs the linter and checks for errors - fixjsstyle.py - tries to fix errors automatically diff --git a/tools/closure_linter/build/lib/closure_linter/__init__.py b/tools/closure_linter/build/lib/closure_linter/__init__.py deleted file mode 100644 index 1798c8cfff57fa..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Package indicator for gjslint.""" diff --git a/tools/closure_linter/build/lib/closure_linter/aliaspass.py b/tools/closure_linter/build/lib/closure_linter/aliaspass.py deleted file mode 100644 index bb37bfa07b2d90..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/aliaspass.py +++ /dev/null @@ -1,248 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Pass that scans for goog.scope aliases and lint/usage errors.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('[email protected] (Nathan Naze)') - -from closure_linter import ecmametadatapass -from closure_linter import errors -from closure_linter import javascripttokens -from closure_linter import scopeutil -from closure_linter import tokenutil -from closure_linter.common import error - - -# TODO(nnaze): Create a Pass interface and move this class, EcmaMetaDataPass, -# and related classes onto it. - - -def _GetAliasForIdentifier(identifier, alias_map): - """Returns the aliased_symbol name for an identifier. - - Example usage: - >>> alias_map = {'MyClass': 'goog.foo.MyClass'} - >>> _GetAliasForIdentifier('MyClass.prototype.action', alias_map) - 'goog.foo.MyClass.prototype.action' - - >>> _GetAliasForIdentifier('MyClass.prototype.action', {}) - None - - Args: - identifier: The identifier. - alias_map: A dictionary mapping a symbol to an alias. - - Returns: - The aliased symbol name or None if not found. - """ - ns = identifier.split('.', 1)[0] - aliased_symbol = alias_map.get(ns) - if aliased_symbol: - return aliased_symbol + identifier[len(ns):] - - -def _SetTypeAlias(js_type, alias_map): - """Updates the alias for identifiers in a type. - - Args: - js_type: A typeannotation.TypeAnnotation instance. - alias_map: A dictionary mapping a symbol to an alias. - """ - aliased_symbol = _GetAliasForIdentifier(js_type.identifier, alias_map) - if aliased_symbol: - js_type.alias = aliased_symbol - for sub_type in js_type.IterTypes(): - _SetTypeAlias(sub_type, alias_map) - - -class AliasPass(object): - """Pass to identify goog.scope() usages. - - Identifies goog.scope() usages and finds lint/usage errors. Notes any - aliases of symbols in Closurized namespaces (that is, reassignments - such as "var MyClass = goog.foo.MyClass;") and annotates identifiers - when they're using an alias (so they may be expanded to the full symbol - later -- that "MyClass.prototype.action" refers to - "goog.foo.MyClass.prototype.action" when expanded.). - """ - - def __init__(self, closurized_namespaces=None, error_handler=None): - """Creates a new pass. - - Args: - closurized_namespaces: A set of Closurized namespaces (e.g. 'goog'). - error_handler: An error handler to report lint errors to. - """ - - self._error_handler = error_handler - - # If we have namespaces, freeze the set. - if closurized_namespaces: - closurized_namespaces = frozenset(closurized_namespaces) - - self._closurized_namespaces = closurized_namespaces - - def Process(self, start_token): - """Runs the pass on a token stream. - - Args: - start_token: The first token in the stream. - """ - - if start_token is None: - return - - # TODO(nnaze): Add more goog.scope usage checks. - self._CheckGoogScopeCalls(start_token) - - # If we have closurized namespaces, identify aliased identifiers. - if self._closurized_namespaces: - context = start_token.metadata.context - root_context = context.GetRoot() - self._ProcessRootContext(root_context) - - def _CheckGoogScopeCalls(self, start_token): - """Check goog.scope calls for lint/usage errors.""" - - def IsScopeToken(token): - return (token.type is javascripttokens.JavaScriptTokenType.IDENTIFIER and - token.string == 'goog.scope') - - # Find all the goog.scope tokens in the file - scope_tokens = [t for t in start_token if IsScopeToken(t)] - - for token in scope_tokens: - scope_context = token.metadata.context - - if not (scope_context.type == ecmametadatapass.EcmaContext.STATEMENT and - scope_context.parent.type == ecmametadatapass.EcmaContext.ROOT): - self._MaybeReportError( - error.Error(errors.INVALID_USE_OF_GOOG_SCOPE, - 'goog.scope call not in global scope', token)) - - # There should be only one goog.scope reference. Register errors for - # every instance after the first. - for token in scope_tokens[1:]: - self._MaybeReportError( - error.Error(errors.EXTRA_GOOG_SCOPE_USAGE, - 'More than one goog.scope call in file.', token)) - - def _MaybeReportError(self, err): - """Report an error to the handler (if registered).""" - if self._error_handler: - self._error_handler.HandleError(err) - - @classmethod - def _YieldAllContexts(cls, context): - """Yields all contexts that are contained by the given context.""" - yield context - for child_context in context.children: - for descendent_child in cls._YieldAllContexts(child_context): - yield descendent_child - - @staticmethod - def _IsTokenInParentBlock(token, parent_block): - """Determines whether the given token is contained by the given block. - - Args: - token: A token - parent_block: An EcmaContext. - - Returns: - Whether the token is in a context that is or is a child of the given - parent_block context. - """ - context = token.metadata.context - - while context: - if context is parent_block: - return True - context = context.parent - - return False - - def _ProcessRootContext(self, root_context): - """Processes all goog.scope blocks under the root context.""" - - assert root_context.type is ecmametadatapass.EcmaContext.ROOT - - # Process aliases in statements in the root scope for goog.module-style - # aliases. - global_alias_map = {} - for context in root_context.children: - if context.type == ecmametadatapass.EcmaContext.STATEMENT: - for statement_child in context.children: - if statement_child.type == ecmametadatapass.EcmaContext.VAR: - match = scopeutil.MatchModuleAlias(statement_child) - if match: - # goog.require aliases cannot use further aliases, the symbol is - # the second part of match, directly. - symbol = match[1] - if scopeutil.IsInClosurizedNamespace(symbol, - self._closurized_namespaces): - global_alias_map[match[0]] = symbol - - # Process each block to find aliases. - for context in root_context.children: - self._ProcessBlock(context, global_alias_map) - - def _ProcessBlock(self, context, global_alias_map): - """Scans a goog.scope block to find aliases and mark alias tokens.""" - alias_map = global_alias_map.copy() - - # Iterate over every token in the context. Each token points to one - # context, but multiple tokens may point to the same context. We only want - # to check each context once, so keep track of those we've seen. - seen_contexts = set() - token = context.start_token - while token and self._IsTokenInParentBlock(token, context): - token_context = token.metadata.context if token.metadata else None - - # Check to see if this token is an alias. - if token_context and token_context not in seen_contexts: - seen_contexts.add(token_context) - - # If this is a alias statement in the goog.scope block. - if (token_context.type == ecmametadatapass.EcmaContext.VAR and - scopeutil.IsGoogScopeBlock(token_context.parent.parent)): - match = scopeutil.MatchAlias(token_context) - - # If this is an alias, remember it in the map. - if match: - alias, symbol = match - symbol = _GetAliasForIdentifier(symbol, alias_map) or symbol - if scopeutil.IsInClosurizedNamespace(symbol, - self._closurized_namespaces): - alias_map[alias] = symbol - - # If this token is an identifier that matches an alias, - # mark the token as an alias to the original symbol. - if (token.type is javascripttokens.JavaScriptTokenType.SIMPLE_LVALUE or - token.type is javascripttokens.JavaScriptTokenType.IDENTIFIER): - identifier = tokenutil.GetIdentifierForToken(token) - if identifier: - aliased_symbol = _GetAliasForIdentifier(identifier, alias_map) - if aliased_symbol: - token.metadata.aliased_symbol = aliased_symbol - - elif token.type == javascripttokens.JavaScriptTokenType.DOC_FLAG: - flag = token.attached_object - if flag and flag.HasType() and flag.jstype: - _SetTypeAlias(flag.jstype, alias_map) - - token = token.next # Get next token diff --git a/tools/closure_linter/build/lib/closure_linter/aliaspass_test.py b/tools/closure_linter/build/lib/closure_linter/aliaspass_test.py deleted file mode 100644 index 7042e5348763cb..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/aliaspass_test.py +++ /dev/null @@ -1,191 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Unit tests for the aliaspass module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('[email protected] (Nathan Naze)') - -import unittest as googletest - -from closure_linter import aliaspass -from closure_linter import errors -from closure_linter import javascriptstatetracker -from closure_linter import testutil -from closure_linter.common import erroraccumulator - - -def _GetTokenByLineAndString(start_token, string, line_number): - for token in start_token: - if token.line_number == line_number and token.string == string: - return token - - -class AliasPassTest(googletest.TestCase): - - def testInvalidGoogScopeCall(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_SCOPE_SCRIPT) - - error_accumulator = erroraccumulator.ErrorAccumulator() - alias_pass = aliaspass.AliasPass( - error_handler=error_accumulator) - alias_pass.Process(start_token) - - alias_errors = error_accumulator.GetErrors() - self.assertEquals(1, len(alias_errors)) - - alias_error = alias_errors[0] - - self.assertEquals(errors.INVALID_USE_OF_GOOG_SCOPE, alias_error.code) - self.assertEquals('goog.scope', alias_error.token.string) - - def testAliasedIdentifiers(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_ALIAS_SCRIPT) - alias_pass = aliaspass.AliasPass(set(['goog', 'myproject'])) - alias_pass.Process(start_token) - - alias_token = _GetTokenByLineAndString(start_token, 'Event', 4) - self.assertTrue(alias_token.metadata.is_alias_definition) - - my_class_token = _GetTokenByLineAndString(start_token, 'myClass', 9) - self.assertIsNone(my_class_token.metadata.aliased_symbol) - - component_token = _GetTokenByLineAndString(start_token, 'Component', 17) - self.assertEquals('goog.ui.Component', - component_token.metadata.aliased_symbol) - - event_token = _GetTokenByLineAndString(start_token, 'Event.Something', 17) - self.assertEquals('goog.events.Event.Something', - event_token.metadata.aliased_symbol) - - non_closurized_token = _GetTokenByLineAndString( - start_token, 'NonClosurizedClass', 18) - self.assertIsNone(non_closurized_token.metadata.aliased_symbol) - - long_start_token = _GetTokenByLineAndString(start_token, 'Event', 24) - self.assertEquals('goog.events.Event.MultilineIdentifier.someMethod', - long_start_token.metadata.aliased_symbol) - - def testAliasedDoctypes(self): - """Tests that aliases are correctly expanded within type annotations.""" - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_ALIAS_SCRIPT) - tracker = javascriptstatetracker.JavaScriptStateTracker() - tracker.DocFlagPass(start_token, error_handler=None) - - alias_pass = aliaspass.AliasPass(set(['goog', 'myproject'])) - alias_pass.Process(start_token) - - flag_token = _GetTokenByLineAndString(start_token, '@type', 22) - self.assertEquals( - 'goog.events.Event.>', - repr(flag_token.attached_object.jstype)) - - def testModuleAlias(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(""" -goog.module('goog.test'); -var Alias = goog.require('goog.Alias'); -Alias.use(); -""") - alias_pass = aliaspass.AliasPass(set(['goog'])) - alias_pass.Process(start_token) - alias_token = _GetTokenByLineAndString(start_token, 'Alias', 3) - self.assertTrue(alias_token.metadata.is_alias_definition) - - def testMultipleGoogScopeCalls(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass( - _TEST_MULTIPLE_SCOPE_SCRIPT) - - error_accumulator = erroraccumulator.ErrorAccumulator() - - alias_pass = aliaspass.AliasPass( - set(['goog', 'myproject']), - error_handler=error_accumulator) - alias_pass.Process(start_token) - - alias_errors = error_accumulator.GetErrors() - - self.assertEquals(3, len(alias_errors)) - - error = alias_errors[0] - self.assertEquals(errors.INVALID_USE_OF_GOOG_SCOPE, error.code) - self.assertEquals(7, error.token.line_number) - - error = alias_errors[1] - self.assertEquals(errors.EXTRA_GOOG_SCOPE_USAGE, error.code) - self.assertEquals(7, error.token.line_number) - - error = alias_errors[2] - self.assertEquals(errors.EXTRA_GOOG_SCOPE_USAGE, error.code) - self.assertEquals(11, error.token.line_number) - - -_TEST_ALIAS_SCRIPT = """ -goog.scope(function() { -var events = goog.events; // scope alias -var Event = events. - Event; // nested multiline scope alias - -// This should not be registered as an aliased identifier because -// it appears before the alias. -var myClass = new MyClass(); - -var Component = goog.ui.Component; // scope alias -var MyClass = myproject.foo.MyClass; // scope alias - -// Scope alias of non-Closurized namespace. -var NonClosurizedClass = aaa.bbb.NonClosurizedClass; - -var component = new Component(Event.Something); -var nonClosurized = NonClosurizedClass(); - -/** - * A created namespace with a really long identifier. - * @type {events.Event.} - */ -Event. - MultilineIdentifier. - someMethod = function() {}; -}); -""" - -_TEST_SCOPE_SCRIPT = """ -function foo () { - // This goog.scope call is invalid. - goog.scope(function() { - - }); -} -""" - -_TEST_MULTIPLE_SCOPE_SCRIPT = """ -goog.scope(function() { - // do nothing -}); - -function foo() { - var test = goog.scope; // We should not see goog.scope mentioned. -} - -// This goog.scope invalid. There can be only one. -goog.scope(function() { - -}); -""" - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/checker.py b/tools/closure_linter/build/lib/closure_linter/checker.py deleted file mode 100644 index 1c984173b06639..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/checker.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Core methods for checking JS files for common style guide violations.""" - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)') - -import gflags as flags - -from closure_linter import aliaspass -from closure_linter import checkerbase -from closure_linter import closurizednamespacesinfo -from closure_linter import javascriptlintrules - - -flags.DEFINE_list('closurized_namespaces', '', - 'Namespace prefixes, used for testing of' - 'goog.provide/require') -flags.DEFINE_list('ignored_extra_namespaces', '', - 'Fully qualified namespaces that should be not be reported ' - 'as extra by the linter.') - - -class JavaScriptStyleChecker(checkerbase.CheckerBase): - """Checker that applies JavaScriptLintRules.""" - - def __init__(self, state_tracker, error_handler): - """Initialize an JavaScriptStyleChecker object. - - Args: - state_tracker: State tracker. - error_handler: Error handler to pass all errors to. - """ - self._namespaces_info = None - self._alias_pass = None - if flags.FLAGS.closurized_namespaces: - self._namespaces_info = ( - closurizednamespacesinfo.ClosurizedNamespacesInfo( - flags.FLAGS.closurized_namespaces, - flags.FLAGS.ignored_extra_namespaces)) - - self._alias_pass = aliaspass.AliasPass( - flags.FLAGS.closurized_namespaces, error_handler) - - checkerbase.CheckerBase.__init__( - self, - error_handler=error_handler, - lint_rules=javascriptlintrules.JavaScriptLintRules( - self._namespaces_info), - state_tracker=state_tracker) - - def Check(self, start_token, limited_doc_checks=False, is_html=False, - stop_token=None): - """Checks a token stream for lint warnings/errors. - - Adds a separate pass for computing dependency information based on - goog.require and goog.provide statements prior to the main linting pass. - - Args: - start_token: The first token in the token stream. - limited_doc_checks: Whether to perform limited checks. - is_html: Whether this token stream is HTML. - stop_token: If given, checks should stop at this token. - """ - self._lint_rules.Initialize(self, limited_doc_checks, is_html) - - self._state_tracker.DocFlagPass(start_token, self._error_handler) - - if self._alias_pass: - self._alias_pass.Process(start_token) - - # To maximize the amount of errors that get reported before a parse error - # is displayed, don't run the dependency pass if a parse error exists. - if self._namespaces_info: - self._namespaces_info.Reset() - self._ExecutePass(start_token, self._DependencyPass, stop_token) - - self._ExecutePass(start_token, self._LintPass, stop_token) - - # If we have a stop_token, we didn't end up reading the whole file and, - # thus, don't call Finalize to do end-of-file checks. - if not stop_token: - self._lint_rules.Finalize(self._state_tracker) - - def _DependencyPass(self, token): - """Processes an individual token for dependency information. - - Used to encapsulate the logic needed to process an individual token so that - it can be passed to _ExecutePass. - - Args: - token: The token to process. - """ - self._namespaces_info.ProcessToken(token, self._state_tracker) diff --git a/tools/closure_linter/build/lib/closure_linter/checkerbase.py b/tools/closure_linter/build/lib/closure_linter/checkerbase.py deleted file mode 100644 index 6679ded05be1e1..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/checkerbase.py +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Base classes for writing checkers that operate on tokens.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)', - '[email protected] (Jacob Richman)') - -from closure_linter import errorrules -from closure_linter.common import error - - -class LintRulesBase(object): - """Base class for all classes defining the lint rules for a language.""" - - def __init__(self): - self.__checker = None - - def Initialize(self, checker, limited_doc_checks, is_html): - """Initializes to prepare to check a file. - - Args: - checker: Class to report errors to. - limited_doc_checks: Whether doc checking is relaxed for this file. - is_html: Whether the file is an HTML file with extracted contents. - """ - self.__checker = checker - self._limited_doc_checks = limited_doc_checks - self._is_html = is_html - - def _HandleError(self, code, message, token, position=None, - fix_data=None): - """Call the HandleError function for the checker we are associated with.""" - if errorrules.ShouldReportError(code): - self.__checker.HandleError(code, message, token, position, fix_data) - - def _SetLimitedDocChecks(self, limited_doc_checks): - """Sets whether doc checking is relaxed for this file. - - Args: - limited_doc_checks: Whether doc checking is relaxed for this file. - """ - self._limited_doc_checks = limited_doc_checks - - def CheckToken(self, token, parser_state): - """Checks a token, given the current parser_state, for warnings and errors. - - Args: - token: The current token under consideration. - parser_state: Object that indicates the parser state in the page. - - Raises: - TypeError: If not overridden. - """ - raise TypeError('Abstract method CheckToken not implemented') - - def Finalize(self, parser_state): - """Perform all checks that need to occur after all lines are processed. - - Args: - parser_state: State of the parser after parsing all tokens - - Raises: - TypeError: If not overridden. - """ - raise TypeError('Abstract method Finalize not implemented') - - -class CheckerBase(object): - """This class handles checking a LintRules object against a file.""" - - def __init__(self, error_handler, lint_rules, state_tracker): - """Initialize a checker object. - - Args: - error_handler: Object that handles errors. - lint_rules: LintRules object defining lint errors given a token - and state_tracker object. - state_tracker: Object that tracks the current state in the token stream. - - """ - self._error_handler = error_handler - self._lint_rules = lint_rules - self._state_tracker = state_tracker - - self._has_errors = False - - def HandleError(self, code, message, token, position=None, - fix_data=None): - """Prints out the given error message including a line number. - - Args: - code: The error code. - message: The error to print. - token: The token where the error occurred, or None if it was a file-wide - issue. - position: The position of the error, defaults to None. - fix_data: Metadata used for fixing the error. - """ - self._has_errors = True - self._error_handler.HandleError( - error.Error(code, message, token, position, fix_data)) - - def HasErrors(self): - """Returns true if the style checker has found any errors. - - Returns: - True if the style checker has found any errors. - """ - return self._has_errors - - def Check(self, start_token, limited_doc_checks=False, is_html=False, - stop_token=None): - """Checks a token stream, reporting errors to the error reporter. - - Args: - start_token: First token in token stream. - limited_doc_checks: Whether doc checking is relaxed for this file. - is_html: Whether the file being checked is an HTML file with extracted - contents. - stop_token: If given, check should stop at this token. - """ - - self._lint_rules.Initialize(self, limited_doc_checks, is_html) - self._ExecutePass(start_token, self._LintPass, stop_token=stop_token) - self._lint_rules.Finalize(self._state_tracker) - - def _LintPass(self, token): - """Checks an individual token for lint warnings/errors. - - Used to encapsulate the logic needed to check an individual token so that it - can be passed to _ExecutePass. - - Args: - token: The token to check. - """ - self._lint_rules.CheckToken(token, self._state_tracker) - - def _ExecutePass(self, token, pass_function, stop_token=None): - """Calls the given function for every token in the given token stream. - - As each token is passed to the given function, state is kept up to date and, - depending on the error_trace flag, errors are either caught and reported, or - allowed to bubble up so developers can see the full stack trace. If a parse - error is specified, the pass will proceed as normal until the token causing - the parse error is reached. - - Args: - token: The first token in the token stream. - pass_function: The function to call for each token in the token stream. - stop_token: The last token to check (if given). - - Raises: - Exception: If any error occurred while calling the given function. - """ - - self._state_tracker.Reset() - while token: - # When we are looking at a token and decided to delete the whole line, we - # will delete all of them in the "HandleToken()" below. So the current - # token and subsequent ones may already be deleted here. The way we - # delete a token does not wipe out the previous and next pointers of the - # deleted token. So we need to check the token itself to make sure it is - # not deleted. - if not token.is_deleted: - # End the pass at the stop token - if stop_token and token is stop_token: - return - - self._state_tracker.HandleToken( - token, self._state_tracker.GetLastNonSpaceToken()) - pass_function(token) - self._state_tracker.HandleAfterToken(token) - - token = token.next diff --git a/tools/closure_linter/build/lib/closure_linter/closurizednamespacesinfo.py b/tools/closure_linter/build/lib/closure_linter/closurizednamespacesinfo.py deleted file mode 100644 index e7cbfd3318974b..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/closurizednamespacesinfo.py +++ /dev/null @@ -1,578 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Logic for computing dependency information for closurized JavaScript files. - -Closurized JavaScript files express dependencies using goog.require and -goog.provide statements. In order for the linter to detect when a statement is -missing or unnecessary, all identifiers in the JavaScript file must first be -processed to determine if they constitute the creation or usage of a dependency. -""" - - - -import re - -from closure_linter import javascripttokens -from closure_linter import tokenutil - -# pylint: disable=g-bad-name -TokenType = javascripttokens.JavaScriptTokenType - -DEFAULT_EXTRA_NAMESPACES = [ - 'goog.testing.asserts', - 'goog.testing.jsunit', -] - - -class UsedNamespace(object): - """A type for information about a used namespace.""" - - def __init__(self, namespace, identifier, token, alias_definition): - """Initializes the instance. - - Args: - namespace: the namespace of an identifier used in the file - identifier: the complete identifier - token: the token that uses the namespace - alias_definition: a boolean stating whether the namespace is only to used - for an alias definition and should not be required. - """ - self.namespace = namespace - self.identifier = identifier - self.token = token - self.alias_definition = alias_definition - - def GetLine(self): - return self.token.line_number - - def __repr__(self): - return 'UsedNamespace(%s)' % ', '.join( - ['%s=%s' % (k, repr(v)) for k, v in self.__dict__.iteritems()]) - - -class ClosurizedNamespacesInfo(object): - """Dependency information for closurized JavaScript files. - - Processes token streams for dependency creation or usage and provides logic - for determining if a given require or provide statement is unnecessary or if - there are missing require or provide statements. - """ - - def __init__(self, closurized_namespaces, ignored_extra_namespaces): - """Initializes an instance the ClosurizedNamespacesInfo class. - - Args: - closurized_namespaces: A list of namespace prefixes that should be - processed for dependency information. Non-matching namespaces are - ignored. - ignored_extra_namespaces: A list of namespaces that should not be reported - as extra regardless of whether they are actually used. - """ - self._closurized_namespaces = closurized_namespaces - self._ignored_extra_namespaces = (ignored_extra_namespaces + - DEFAULT_EXTRA_NAMESPACES) - self.Reset() - - def Reset(self): - """Resets the internal state to prepare for processing a new file.""" - - # A list of goog.provide tokens in the order they appeared in the file. - self._provide_tokens = [] - - # A list of goog.require tokens in the order they appeared in the file. - self._require_tokens = [] - - # Namespaces that are already goog.provided. - self._provided_namespaces = [] - - # Namespaces that are already goog.required. - self._required_namespaces = [] - - # Note that created_namespaces and used_namespaces contain both namespaces - # and identifiers because there are many existing cases where a method or - # constant is provided directly instead of its namespace. Ideally, these - # two lists would only have to contain namespaces. - - # A list of tuples where the first element is the namespace of an identifier - # created in the file, the second is the identifier itself and the third is - # the line number where it's created. - self._created_namespaces = [] - - # A list of UsedNamespace instances. - self._used_namespaces = [] - - # A list of seemingly-unnecessary namespaces that are goog.required() and - # annotated with @suppress {extraRequire}. - self._suppressed_requires = [] - - # A list of goog.provide tokens which are duplicates. - self._duplicate_provide_tokens = [] - - # A list of goog.require tokens which are duplicates. - self._duplicate_require_tokens = [] - - # Whether this file is in a goog.scope. Someday, we may add support - # for checking scopified namespaces, but for now let's just fail - # in a more reasonable way. - self._scopified_file = False - - # TODO(user): Handle the case where there are 2 different requires - # that can satisfy the same dependency, but only one is necessary. - - def GetProvidedNamespaces(self): - """Returns the namespaces which are already provided by this file. - - Returns: - A list of strings where each string is a 'namespace' corresponding to an - existing goog.provide statement in the file being checked. - """ - return set(self._provided_namespaces) - - def GetRequiredNamespaces(self): - """Returns the namespaces which are already required by this file. - - Returns: - A list of strings where each string is a 'namespace' corresponding to an - existing goog.require statement in the file being checked. - """ - return set(self._required_namespaces) - - def IsExtraProvide(self, token): - """Returns whether the given goog.provide token is unnecessary. - - Args: - token: A goog.provide token. - - Returns: - True if the given token corresponds to an unnecessary goog.provide - statement, otherwise False. - """ - namespace = tokenutil.GetStringAfterToken(token) - - if self.GetClosurizedNamespace(namespace) is None: - return False - - if token in self._duplicate_provide_tokens: - return True - - # TODO(user): There's probably a faster way to compute this. - for created_namespace, created_identifier, _ in self._created_namespaces: - if namespace == created_namespace or namespace == created_identifier: - return False - - return True - - def IsExtraRequire(self, token): - """Returns whether the given goog.require token is unnecessary. - - Args: - token: A goog.require token. - - Returns: - True if the given token corresponds to an unnecessary goog.require - statement, otherwise False. - """ - namespace = tokenutil.GetStringAfterToken(token) - - if self.GetClosurizedNamespace(namespace) is None: - return False - - if namespace in self._ignored_extra_namespaces: - return False - - if token in self._duplicate_require_tokens: - return True - - if namespace in self._suppressed_requires: - return False - - # If the namespace contains a component that is initial caps, then that - # must be the last component of the namespace. - parts = namespace.split('.') - if len(parts) > 1 and parts[-2][0].isupper(): - return True - - # TODO(user): There's probably a faster way to compute this. - for ns in self._used_namespaces: - if (not ns.alias_definition and ( - namespace == ns.namespace or namespace == ns.identifier)): - return False - - return True - - def GetMissingProvides(self): - """Returns the dict of missing provided namespaces for the current file. - - Returns: - Returns a dictionary of key as string and value as integer where each - string(key) is a namespace that should be provided by this file, but is - not and integer(value) is first line number where it's defined. - """ - missing_provides = dict() - for namespace, identifier, line_number in self._created_namespaces: - if (not self._IsPrivateIdentifier(identifier) and - namespace not in self._provided_namespaces and - identifier not in self._provided_namespaces and - namespace not in self._required_namespaces and - namespace not in missing_provides): - missing_provides[namespace] = line_number - - return missing_provides - - def GetMissingRequires(self): - """Returns the dict of missing required namespaces for the current file. - - For each non-private identifier used in the file, find either a - goog.require, goog.provide or a created identifier that satisfies it. - goog.require statements can satisfy the identifier by requiring either the - namespace of the identifier or the identifier itself. goog.provide - statements can satisfy the identifier by providing the namespace of the - identifier. A created identifier can only satisfy the used identifier if - it matches it exactly (necessary since things can be defined on a - namespace in more than one file). Note that provided namespaces should be - a subset of created namespaces, but we check both because in some cases we - can't always detect the creation of the namespace. - - Returns: - Returns a dictionary of key as string and value integer where each - string(key) is a namespace that should be required by this file, but is - not and integer(value) is first line number where it's used. - """ - external_dependencies = set(self._required_namespaces) - - # Assume goog namespace is always available. - external_dependencies.add('goog') - # goog.module is treated as a builtin, too (for goog.module.get). - external_dependencies.add('goog.module') - - created_identifiers = set() - for unused_namespace, identifier, unused_line_number in ( - self._created_namespaces): - created_identifiers.add(identifier) - - missing_requires = dict() - illegal_alias_statements = dict() - - def ShouldRequireNamespace(namespace, identifier): - """Checks if a namespace would normally be required.""" - return ( - not self._IsPrivateIdentifier(identifier) and - namespace not in external_dependencies and - namespace not in self._provided_namespaces and - identifier not in external_dependencies and - identifier not in created_identifiers and - namespace not in missing_requires) - - # First check all the used identifiers where we know that their namespace - # needs to be provided (unless they are optional). - for ns in self._used_namespaces: - namespace = ns.namespace - identifier = ns.identifier - if (not ns.alias_definition and - ShouldRequireNamespace(namespace, identifier)): - missing_requires[namespace] = ns.GetLine() - - # Now that all required namespaces are known, we can check if the alias - # definitions (that are likely being used for typeannotations that don't - # need explicit goog.require statements) are already covered. If not - # the user shouldn't use the alias. - for ns in self._used_namespaces: - if (not ns.alias_definition or - not ShouldRequireNamespace(ns.namespace, ns.identifier)): - continue - if self._FindNamespace(ns.identifier, self._provided_namespaces, - created_identifiers, external_dependencies, - missing_requires): - continue - namespace = ns.identifier.rsplit('.', 1)[0] - illegal_alias_statements[namespace] = ns.token - - return missing_requires, illegal_alias_statements - - def _FindNamespace(self, identifier, *namespaces_list): - """Finds the namespace of an identifier given a list of other namespaces. - - Args: - identifier: An identifier whose parent needs to be defined. - e.g. for goog.bar.foo we search something that provides - goog.bar. - *namespaces_list: var args of iterables of namespace identifiers - Returns: - The namespace that the given identifier is part of or None. - """ - identifier = identifier.rsplit('.', 1)[0] - identifier_prefix = identifier + '.' - for namespaces in namespaces_list: - for namespace in namespaces: - if namespace == identifier or namespace.startswith(identifier_prefix): - return namespace - return None - - def _IsPrivateIdentifier(self, identifier): - """Returns whether the given identifier is private.""" - pieces = identifier.split('.') - for piece in pieces: - if piece.endswith('_'): - return True - return False - - def IsFirstProvide(self, token): - """Returns whether token is the first provide token.""" - return self._provide_tokens and token == self._provide_tokens[0] - - def IsFirstRequire(self, token): - """Returns whether token is the first require token.""" - return self._require_tokens and token == self._require_tokens[0] - - def IsLastProvide(self, token): - """Returns whether token is the last provide token.""" - return self._provide_tokens and token == self._provide_tokens[-1] - - def IsLastRequire(self, token): - """Returns whether token is the last require token.""" - return self._require_tokens and token == self._require_tokens[-1] - - def ProcessToken(self, token, state_tracker): - """Processes the given token for dependency information. - - Args: - token: The token to process. - state_tracker: The JavaScript state tracker. - """ - - # Note that this method is in the critical path for the linter and has been - # optimized for performance in the following ways: - # - Tokens are checked by type first to minimize the number of function - # calls necessary to determine if action needs to be taken for the token. - # - The most common tokens types are checked for first. - # - The number of function calls has been minimized (thus the length of this - # function. - - if token.type == TokenType.IDENTIFIER: - # TODO(user): Consider saving the whole identifier in metadata. - whole_identifier_string = tokenutil.GetIdentifierForToken(token) - if whole_identifier_string is None: - # We only want to process the identifier one time. If the whole string - # identifier is None, that means this token was part of a multi-token - # identifier, but it was not the first token of the identifier. - return - - # In the odd case that a goog.require is encountered inside a function, - # just ignore it (e.g. dynamic loading in test runners). - if token.string == 'goog.require' and not state_tracker.InFunction(): - self._require_tokens.append(token) - namespace = tokenutil.GetStringAfterToken(token) - if namespace in self._required_namespaces: - self._duplicate_require_tokens.append(token) - else: - self._required_namespaces.append(namespace) - - # If there is a suppression for the require, add a usage for it so it - # gets treated as a regular goog.require (i.e. still gets sorted). - if self._HasSuppression(state_tracker, 'extraRequire'): - self._suppressed_requires.append(namespace) - self._AddUsedNamespace(state_tracker, namespace, token) - - elif token.string == 'goog.provide': - self._provide_tokens.append(token) - namespace = tokenutil.GetStringAfterToken(token) - if namespace in self._provided_namespaces: - self._duplicate_provide_tokens.append(token) - else: - self._provided_namespaces.append(namespace) - - # If there is a suppression for the provide, add a creation for it so it - # gets treated as a regular goog.provide (i.e. still gets sorted). - if self._HasSuppression(state_tracker, 'extraProvide'): - self._AddCreatedNamespace(state_tracker, namespace, token.line_number) - - elif token.string == 'goog.scope': - self._scopified_file = True - - elif token.string == 'goog.setTestOnly': - - # Since the message is optional, we don't want to scan to later lines. - for t in tokenutil.GetAllTokensInSameLine(token): - if t.type == TokenType.STRING_TEXT: - message = t.string - - if re.match(r'^\w+(\.\w+)+$', message): - # This looks like a namespace. If it's a Closurized namespace, - # consider it created. - base_namespace = message.split('.', 1)[0] - if base_namespace in self._closurized_namespaces: - self._AddCreatedNamespace(state_tracker, message, - token.line_number) - - break - else: - jsdoc = state_tracker.GetDocComment() - if token.metadata and token.metadata.aliased_symbol: - whole_identifier_string = token.metadata.aliased_symbol - elif (token.string == 'goog.module.get' and - not self._HasSuppression(state_tracker, 'extraRequire')): - # Cannot use _AddUsedNamespace as this is not an identifier, but - # already the entire namespace that's required. - namespace = tokenutil.GetStringAfterToken(token) - namespace = UsedNamespace(namespace, namespace, token, - alias_definition=False) - self._used_namespaces.append(namespace) - if jsdoc and jsdoc.HasFlag('typedef'): - self._AddCreatedNamespace(state_tracker, whole_identifier_string, - token.line_number, - namespace=self.GetClosurizedNamespace( - whole_identifier_string)) - else: - is_alias_definition = (token.metadata and - token.metadata.is_alias_definition) - self._AddUsedNamespace(state_tracker, whole_identifier_string, - token, is_alias_definition) - - elif token.type == TokenType.SIMPLE_LVALUE: - identifier = token.values['identifier'] - start_token = tokenutil.GetIdentifierStart(token) - if start_token and start_token != token: - # Multi-line identifier being assigned. Get the whole identifier. - identifier = tokenutil.GetIdentifierForToken(start_token) - else: - start_token = token - # If an alias is defined on the start_token, use it instead. - if (start_token and - start_token.metadata and - start_token.metadata.aliased_symbol and - not start_token.metadata.is_alias_definition): - identifier = start_token.metadata.aliased_symbol - - if identifier: - namespace = self.GetClosurizedNamespace(identifier) - if state_tracker.InFunction(): - self._AddUsedNamespace(state_tracker, identifier, token) - elif namespace and namespace != 'goog': - self._AddCreatedNamespace(state_tracker, identifier, - token.line_number, namespace=namespace) - - elif token.type == TokenType.DOC_FLAG: - flag = token.attached_object - flag_type = flag.flag_type - if flag and flag.HasType() and flag.jstype: - is_interface = state_tracker.GetDocComment().HasFlag('interface') - if flag_type == 'implements' or (flag_type == 'extends' - and is_interface): - identifier = flag.jstype.alias or flag.jstype.identifier - self._AddUsedNamespace(state_tracker, identifier, token) - # Since we process doctypes only for implements and extends, the - # type is a simple one and we don't need any iteration for subtypes. - - def _AddCreatedNamespace(self, state_tracker, identifier, line_number, - namespace=None): - """Adds the namespace of an identifier to the list of created namespaces. - - If the identifier is annotated with a 'missingProvide' suppression, it is - not added. - - Args: - state_tracker: The JavaScriptStateTracker instance. - identifier: The identifier to add. - line_number: Line number where namespace is created. - namespace: The namespace of the identifier or None if the identifier is - also the namespace. - """ - if not namespace: - namespace = identifier - - if self._HasSuppression(state_tracker, 'missingProvide'): - return - - self._created_namespaces.append([namespace, identifier, line_number]) - - def _AddUsedNamespace(self, state_tracker, identifier, token, - is_alias_definition=False): - """Adds the namespace of an identifier to the list of used namespaces. - - If the identifier is annotated with a 'missingRequire' suppression, it is - not added. - - Args: - state_tracker: The JavaScriptStateTracker instance. - identifier: An identifier which has been used. - token: The token in which the namespace is used. - is_alias_definition: If the used namespace is part of an alias_definition. - Aliased symbols need their parent namespace to be available, if it is - not yet required through another symbol, an error will be thrown. - """ - if self._HasSuppression(state_tracker, 'missingRequire'): - return - - namespace = self.GetClosurizedNamespace(identifier) - # b/5362203 If its a variable in scope then its not a required namespace. - if namespace and not state_tracker.IsVariableInScope(namespace): - namespace = UsedNamespace(namespace, identifier, token, - is_alias_definition) - self._used_namespaces.append(namespace) - - def _HasSuppression(self, state_tracker, suppression): - jsdoc = state_tracker.GetDocComment() - return jsdoc and suppression in jsdoc.suppressions - - def GetClosurizedNamespace(self, identifier): - """Given an identifier, returns the namespace that identifier is from. - - Args: - identifier: The identifier to extract a namespace from. - - Returns: - The namespace the given identifier resides in, or None if one could not - be found. - """ - if identifier.startswith('goog.global'): - # Ignore goog.global, since it is, by definition, global. - return None - - parts = identifier.split('.') - for namespace in self._closurized_namespaces: - if not identifier.startswith(namespace + '.'): - continue - - # The namespace for a class is the shortest prefix ending in a class - # name, which starts with a capital letter but is not a capitalized word. - # - # We ultimately do not want to allow requiring or providing of inner - # classes/enums. Instead, a file should provide only the top-level class - # and users should require only that. - namespace = [] - for part in parts: - if part == 'prototype' or part.isupper(): - return '.'.join(namespace) - namespace.append(part) - if part[0].isupper(): - return '.'.join(namespace) - - # At this point, we know there's no class or enum, so the namespace is - # just the identifier with the last part removed. With the exception of - # apply, inherits, and call, which should also be stripped. - if parts[-1] in ('apply', 'inherits', 'call'): - parts.pop() - parts.pop() - - # If the last part ends with an underscore, it is a private variable, - # method, or enum. The namespace is whatever is before it. - if parts and parts[-1].endswith('_'): - parts.pop() - - return '.'.join(parts) - - return None diff --git a/tools/closure_linter/build/lib/closure_linter/closurizednamespacesinfo_test.py b/tools/closure_linter/build/lib/closure_linter/closurizednamespacesinfo_test.py deleted file mode 100644 index 7aeae21956af8d..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/closurizednamespacesinfo_test.py +++ /dev/null @@ -1,873 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2010 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Unit tests for ClosurizedNamespacesInfo.""" - - - -import unittest as googletest -from closure_linter import aliaspass -from closure_linter import closurizednamespacesinfo -from closure_linter import ecmametadatapass -from closure_linter import javascriptstatetracker -from closure_linter import javascripttokens -from closure_linter import testutil -from closure_linter import tokenutil - -# pylint: disable=g-bad-name -TokenType = javascripttokens.JavaScriptTokenType - - -def _ToLineDict(illegal_alias_stmts): - """Replaces tokens with the respective line number.""" - return {k: v.line_number for k, v in illegal_alias_stmts.iteritems()} - - -class ClosurizedNamespacesInfoTest(googletest.TestCase): - """Tests for ClosurizedNamespacesInfo.""" - - _test_cases = { - 'goog.global.anything': None, - 'package.CONSTANT': 'package', - 'package.methodName': 'package', - 'package.subpackage.methodName': 'package.subpackage', - 'package.subpackage.methodName.apply': 'package.subpackage', - 'package.ClassName.something': 'package.ClassName', - 'package.ClassName.Enum.VALUE.methodName': 'package.ClassName', - 'package.ClassName.CONSTANT': 'package.ClassName', - 'package.namespace.CONSTANT.methodName': 'package.namespace', - 'package.ClassName.inherits': 'package.ClassName', - 'package.ClassName.apply': 'package.ClassName', - 'package.ClassName.methodName.apply': 'package.ClassName', - 'package.ClassName.methodName.call': 'package.ClassName', - 'package.ClassName.prototype.methodName': 'package.ClassName', - 'package.ClassName.privateMethod_': 'package.ClassName', - 'package.className.privateProperty_': 'package.className', - 'package.className.privateProperty_.methodName': 'package.className', - 'package.ClassName.PrivateEnum_': 'package.ClassName', - 'package.ClassName.prototype.methodName.apply': 'package.ClassName', - 'package.ClassName.property.subProperty': 'package.ClassName', - 'package.className.prototype.something.somethingElse': 'package.className' - } - - def testGetClosurizedNamespace(self): - """Tests that the correct namespace is returned for various identifiers.""" - namespaces_info = closurizednamespacesinfo.ClosurizedNamespacesInfo( - closurized_namespaces=['package'], ignored_extra_namespaces=[]) - for identifier, expected_namespace in self._test_cases.items(): - actual_namespace = namespaces_info.GetClosurizedNamespace(identifier) - self.assertEqual( - expected_namespace, - actual_namespace, - 'expected namespace "' + str(expected_namespace) + - '" for identifier "' + str(identifier) + '" but was "' + - str(actual_namespace) + '"') - - def testIgnoredExtraNamespaces(self): - """Tests that ignored_extra_namespaces are ignored.""" - token = self._GetRequireTokens('package.Something') - namespaces_info = closurizednamespacesinfo.ClosurizedNamespacesInfo( - closurized_namespaces=['package'], - ignored_extra_namespaces=['package.Something']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Should be valid since it is in ignored namespaces.') - - namespaces_info = closurizednamespacesinfo.ClosurizedNamespacesInfo( - ['package'], []) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'Should be invalid since it is not in ignored namespaces.') - - def testIsExtraProvide_created(self): - """Tests that provides for created namespaces are not extra.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'package.Foo = function() {};' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraProvide(token), - 'Should not be extra since it is created.') - - def testIsExtraProvide_createdIdentifier(self): - """Tests that provides for created identifiers are not extra.""" - input_lines = [ - 'goog.provide(\'package.Foo.methodName\');', - 'package.Foo.methodName = function() {};' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraProvide(token), - 'Should not be extra since it is created.') - - def testIsExtraProvide_notCreated(self): - """Tests that provides for non-created namespaces are extra.""" - input_lines = ['goog.provide(\'package.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraProvide(token), - 'Should be extra since it is not created.') - - def testIsExtraProvide_notCreatedMultipartClosurizedNamespace(self): - """Tests that provides for non-created namespaces are extra.""" - input_lines = ['goog.provide(\'multi.part.namespace.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['multi.part']) - - self.assertTrue(namespaces_info.IsExtraProvide(token), - 'Should be extra since it is not created.') - - def testIsExtraProvide_duplicate(self): - """Tests that providing a namespace twice makes the second one extra.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'goog.provide(\'package.Foo\');', - 'package.Foo = function() {};' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - # Advance to the second goog.provide token. - token = tokenutil.Search(token.next, TokenType.IDENTIFIER) - - self.assertTrue(namespaces_info.IsExtraProvide(token), - 'Should be extra since it is already provided.') - - def testIsExtraProvide_notClosurized(self): - """Tests that provides of non-closurized namespaces are not extra.""" - input_lines = ['goog.provide(\'notclosurized.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraProvide(token), - 'Should not be extra since it is not closurized.') - - def testIsExtraRequire_used(self): - """Tests that requires for used namespaces are not extra.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'var x = package.Foo.methodName();' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Should not be extra since it is used.') - - def testIsExtraRequire_usedIdentifier(self): - """Tests that requires for used methods on classes are extra.""" - input_lines = [ - 'goog.require(\'package.Foo.methodName\');', - 'var x = package.Foo.methodName();' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'Should require the package, not the method specifically.') - - def testIsExtraRequire_notUsed(self): - """Tests that requires for unused namespaces are extra.""" - input_lines = ['goog.require(\'package.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'Should be extra since it is not used.') - - def testIsExtraRequire_notUsedMultiPartClosurizedNamespace(self): - """Tests unused require with multi-part closurized namespaces.""" - - input_lines = ['goog.require(\'multi.part.namespace.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['multi.part']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'Should be extra since it is not used.') - - def testIsExtraRequire_notClosurized(self): - """Tests that requires of non-closurized namespaces are not extra.""" - input_lines = ['goog.require(\'notclosurized.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Should not be extra since it is not closurized.') - - def testIsExtraRequire_objectOnClass(self): - """Tests that requiring an object on a class is extra.""" - input_lines = [ - 'goog.require(\'package.Foo.Enum\');', - 'var x = package.Foo.Enum.VALUE1;', - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'The whole class, not the object, should be required.'); - - def testIsExtraRequire_constantOnClass(self): - """Tests that requiring a constant on a class is extra.""" - input_lines = [ - 'goog.require(\'package.Foo.CONSTANT\');', - 'var x = package.Foo.CONSTANT', - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'The class, not the constant, should be required.'); - - def testIsExtraRequire_constantNotOnClass(self): - """Tests that requiring a constant not on a class is OK.""" - input_lines = [ - 'goog.require(\'package.subpackage.CONSTANT\');', - 'var x = package.subpackage.CONSTANT', - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Constants can be required except on classes.'); - - def testIsExtraRequire_methodNotOnClass(self): - """Tests that requiring a method not on a class is OK.""" - input_lines = [ - 'goog.require(\'package.subpackage.method\');', - 'var x = package.subpackage.method()', - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Methods can be required except on classes.'); - - def testIsExtraRequire_defaults(self): - """Tests that there are no warnings about extra requires for test utils""" - input_lines = ['goog.require(\'goog.testing.jsunit\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['goog']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Should not be extra since it is for testing.') - - def testGetMissingProvides_provided(self): - """Tests that provided functions don't cause a missing provide.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'package.Foo = function() {};' - ] - - namespaces_info = self._GetNamespacesInfoForScript( - input_lines, ['package']) - - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingProvides_providedIdentifier(self): - """Tests that provided identifiers don't cause a missing provide.""" - input_lines = [ - 'goog.provide(\'package.Foo.methodName\');', - 'package.Foo.methodName = function() {};' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingProvides_providedParentIdentifier(self): - """Tests that provided identifiers on a class don't cause a missing provide - on objects attached to that class.""" - input_lines = [ - 'goog.provide(\'package.foo.ClassName\');', - 'package.foo.ClassName.methodName = function() {};', - 'package.foo.ClassName.ObjectName = 1;', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingProvides_unprovided(self): - """Tests that unprovided functions cause a missing provide.""" - input_lines = ['package.Foo = function() {};'] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - - missing_provides = namespaces_info.GetMissingProvides() - self.assertEquals(1, len(missing_provides)) - missing_provide = missing_provides.popitem() - self.assertEquals('package.Foo', missing_provide[0]) - self.assertEquals(1, missing_provide[1]) - - def testGetMissingProvides_privatefunction(self): - """Tests that unprovided private functions don't cause a missing provide.""" - input_lines = ['package.Foo_ = function() {};'] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingProvides_required(self): - """Tests that required namespaces don't cause a missing provide.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'package.Foo.methodName = function() {};' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingRequires_required(self): - """Tests that required namespaces don't cause a missing require.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'package.Foo();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_requiredIdentifier(self): - """Tests that required namespaces satisfy identifiers on that namespace.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'package.Foo.methodName();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_requiredNamespace(self): - """Tests that required namespaces satisfy the namespace.""" - input_lines = [ - 'goog.require(\'package.soy.fooTemplate\');', - 'render(package.soy.fooTemplate);' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_requiredParentClass(self): - """Tests that requiring a parent class of an object is sufficient to prevent - a missing require on that object.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'package.Foo.methodName();', - 'package.Foo.methodName(package.Foo.ObjectName);' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_unrequired(self): - """Tests that unrequired namespaces cause a missing require.""" - input_lines = ['package.Foo();'] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(1, len(missing_requires)) - missing_req = missing_requires.popitem() - self.assertEquals('package.Foo', missing_req[0]) - self.assertEquals(1, missing_req[1]) - - def testGetMissingRequires_provided(self): - """Tests that provided namespaces satisfy identifiers on that namespace.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'package.Foo.methodName();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_created(self): - """Tests that created namespaces do not satisfy usage of an identifier.""" - input_lines = [ - 'package.Foo = function();', - 'package.Foo.methodName();', - 'package.Foo.anotherMethodName1();', - 'package.Foo.anotherMethodName2();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(1, len(missing_requires)) - missing_require = missing_requires.popitem() - self.assertEquals('package.Foo', missing_require[0]) - # Make sure line number of first occurrence is reported - self.assertEquals(2, missing_require[1]) - - def testGetMissingRequires_createdIdentifier(self): - """Tests that created identifiers satisfy usage of the identifier.""" - input_lines = [ - 'package.Foo.methodName = function();', - 'package.Foo.methodName();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_implements(self): - """Tests that a parametrized type requires the correct identifier.""" - input_lines = [ - '/** @constructor @implements {package.Bar} */', - 'package.Foo = function();', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertItemsEqual({'package.Bar': 1}, missing_requires) - - def testGetMissingRequires_objectOnClass(self): - """Tests that we should require a class, not the object on the class.""" - input_lines = [ - 'goog.require(\'package.Foo.Enum\');', - 'var x = package.Foo.Enum.VALUE1;', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(1, len(missing_requires), - 'The whole class, not the object, should be required.') - - def testGetMissingRequires_variableWithSameName(self): - """Tests that we should not goog.require variables and parameters. - - b/5362203 Variables in scope are not missing namespaces. - """ - input_lines = [ - 'goog.provide(\'Foo\');', - 'Foo.A = function();', - 'Foo.A.prototype.method = function(ab) {', - ' if (ab) {', - ' var docs;', - ' var lvalue = new Obj();', - ' // Variable in scope hence not goog.require here.', - ' docs.foo.abc = 1;', - ' lvalue.next();', - ' }', - ' // Since js is function scope this should also not goog.require.', - ' docs.foo.func();', - ' // Its not a variable in scope hence goog.require.', - ' dummy.xyz.reset();', - ' return this.method2();', - '};', - 'Foo.A.prototype.method1 = function(docs, abcd, xyz) {', - ' // Parameter hence not goog.require.', - ' docs.nodes.length = 2;', - ' lvalue.abc.reset();', - '};' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['Foo', - 'docs', - 'lvalue', - 'dummy']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(2, len(missing_requires)) - self.assertItemsEqual( - {'dummy.xyz': 14, - 'lvalue.abc': 20}, missing_requires) - - def testIsFirstProvide(self): - """Tests operation of the isFirstProvide method.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'package.Foo.methodName();' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - self.assertTrue(namespaces_info.IsFirstProvide(token)) - - def testGetWholeIdentifierString(self): - """Tests that created identifiers satisfy usage of the identifier.""" - input_lines = [ - 'package.Foo.', - ' veryLong.', - ' identifier;' - ] - - token = testutil.TokenizeSource(input_lines) - - self.assertEquals('package.Foo.veryLong.identifier', - tokenutil.GetIdentifierForToken(token)) - - self.assertEquals(None, - tokenutil.GetIdentifierForToken(token.next)) - - def testScopified(self): - """Tests that a goog.scope call is noticed.""" - input_lines = [ - 'goog.scope(function() {', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - self.assertTrue(namespaces_info._scopified_file) - - def testScope_unusedAlias(self): - """Tests that an unused alias symbol is illegal.""" - input_lines = [ - 'goog.scope(function() {', - 'var Event = goog.events.Event;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({'goog.events': 2}, _ToLineDict(illegal_alias_stmts)) - - def testScope_usedMultilevelAlias(self): - """Tests that an used alias symbol in a deep namespace is ok.""" - input_lines = [ - 'goog.require(\'goog.Events\');', - 'goog.scope(function() {', - 'var Event = goog.Events.DeepNamespace.Event;', - 'Event();', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - - def testScope_usedAlias(self): - """Tests that aliased symbols result in correct requires.""" - input_lines = [ - 'goog.scope(function() {', - 'var Event = goog.events.Event;', - 'var dom = goog.dom;', - 'Event(dom.classes.get);', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, illegal_alias_stmts) - self.assertEquals({'goog.dom.classes': 4, 'goog.events.Event': 4}, - missing_requires) - - def testModule_alias(self): - """Tests that goog.module style aliases are supported.""" - input_lines = [ - 'goog.module(\'test.module\');', - 'var Unused = goog.require(\'goog.Unused\');', - 'var AliasedClass = goog.require(\'goog.AliasedClass\');', - 'var x = new AliasedClass();', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - namespaceToken = self._GetRequireTokens('goog.AliasedClass') - self.assertFalse(namespaces_info.IsExtraRequire(namespaceToken), - 'AliasedClass should be marked as used') - unusedToken = self._GetRequireTokens('goog.Unused') - self.assertTrue(namespaces_info.IsExtraRequire(unusedToken), - 'Unused should be marked as not used') - - def testModule_aliasInScope(self): - """Tests that goog.module style aliases are supported.""" - input_lines = [ - 'goog.module(\'test.module\');', - 'var AliasedClass = goog.require(\'goog.AliasedClass\');', - 'goog.scope(function() {', - 'var x = new AliasedClass();', - '});', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - namespaceToken = self._GetRequireTokens('goog.AliasedClass') - self.assertFalse(namespaces_info.IsExtraRequire(namespaceToken), - 'AliasedClass should be marked as used') - - def testModule_getAlwaysProvided(self): - """Tests that goog.module.get is recognized as a built-in.""" - input_lines = [ - 'goog.provide(\'test.MyClass\');', - 'goog.require(\'goog.someModule\');', - 'goog.scope(function() {', - 'var someModule = goog.module.get(\'goog.someModule\');', - 'test.MyClass = function() {};', - '});', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - self.assertEquals({}, namespaces_info.GetMissingRequires()[0]) - - def testModule_requireForGet(self): - """Tests that goog.module.get needs a goog.require call.""" - input_lines = [ - 'goog.provide(\'test.MyClass\');', - 'function foo() {', - ' var someModule = goog.module.get(\'goog.someModule\');', - ' someModule.doSth();', - '}', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - self.assertEquals({'goog.someModule': 3}, - namespaces_info.GetMissingRequires()[0]) - - def testScope_usedTypeAlias(self): - """Tests aliased symbols in type annotations.""" - input_lines = [ - 'goog.scope(function() {', - 'var Event = goog.events.Event;', - '/** @type {Event} */;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({'goog.events': 2}, _ToLineDict(illegal_alias_stmts)) - - def testScope_partialAlias_typeOnly(self): - """Tests a partial alias only used in type annotations. - - In this example, some goog.events namespace would need to be required - so that evaluating goog.events.bar doesn't throw an error. - """ - input_lines = [ - 'goog.scope(function() {', - 'var bar = goog.events.bar;', - '/** @type {bar.Foo} */;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({'goog.events': 2}, _ToLineDict(illegal_alias_stmts)) - - def testScope_partialAlias(self): - """Tests a partial alias in conjunction with a type annotation. - - In this example, the partial alias is already defined by another type, - therefore the doc-only type doesn't need to be required. - """ - input_lines = [ - 'goog.scope(function() {', - 'var bar = goog.events.bar;', - '/** @type {bar.Event} */;', - 'bar.EventType();' - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({'goog.events.bar.EventType': 4}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - - def testScope_partialAliasRequires(self): - """Tests partial aliases with correct requires.""" - input_lines = [ - 'goog.require(\'goog.events.bar.EventType\');', - 'goog.scope(function() {', - 'var bar = goog.events.bar;', - '/** @type {bar.Event} */;', - 'bar.EventType();' - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - - def testScope_partialAliasRequiresBoth(self): - """Tests partial aliases with correct requires.""" - input_lines = [ - 'goog.require(\'goog.events.bar.Event\');', - 'goog.require(\'goog.events.bar.EventType\');', - 'goog.scope(function() {', - 'var bar = goog.events.bar;', - '/** @type {bar.Event} */;', - 'bar.EventType();' - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - event_token = self._GetRequireTokens('goog.events.bar.Event') - self.assertTrue(namespaces_info.IsExtraRequire(event_token)) - - def testScope_partialAliasNoSubtypeRequires(self): - """Tests that partial aliases don't yield subtype requires (regression).""" - input_lines = [ - 'goog.provide(\'goog.events.Foo\');', - 'goog.scope(function() {', - 'goog.events.Foo = {};', - 'var Foo = goog.events.Foo;' - 'Foo.CssName_ = {};' - 'var CssName_ = Foo.CssName_;' - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - - def testScope_aliasNamespace(self): - """Tests that an unused alias namespace is not required when available. - - In the example goog.events.Bar is not required, because the namespace - goog.events is already defined because goog.events.Foo is required. - """ - input_lines = [ - 'goog.require(\'goog.events.Foo\');', - 'goog.scope(function() {', - 'var Bar = goog.events.Bar;', - '/** @type {Bar} */;', - 'goog.events.Foo;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - - def testScope_aliasNamespaceIllegal(self): - """Tests that an unused alias namespace is not required when available.""" - input_lines = [ - 'goog.scope(function() {', - 'var Bar = goog.events.Bar;', - '/** @type {Bar} */;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({'goog.events': 2}, _ToLineDict(illegal_alias_stmts)) - - def testScope_provides(self): - """Tests that aliased symbols result in correct provides.""" - input_lines = [ - 'goog.scope(function() {', - 'goog.bar = {};', - 'var bar = goog.bar;', - 'bar.Foo = {};', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_provides = namespaces_info.GetMissingProvides() - self.assertEquals({'goog.bar.Foo': 4}, missing_provides) - _, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, illegal_alias_stmts) - - def testSetTestOnlyNamespaces(self): - """Tests that a namespace in setTestOnly makes it a valid provide.""" - namespaces_info = self._GetNamespacesInfoForScript([ - 'goog.setTestOnly(\'goog.foo.barTest\');' - ], ['goog']) - - token = self._GetProvideTokens('goog.foo.barTest') - self.assertFalse(namespaces_info.IsExtraProvide(token)) - - token = self._GetProvideTokens('goog.foo.bazTest') - self.assertTrue(namespaces_info.IsExtraProvide(token)) - - def testSetTestOnlyComment(self): - """Ensure a comment in setTestOnly does not cause a created namespace.""" - namespaces_info = self._GetNamespacesInfoForScript([ - 'goog.setTestOnly(\'this is a comment\');' - ], ['goog']) - - self.assertEquals( - [], namespaces_info._created_namespaces, - 'A comment in setTestOnly should not modify created namespaces.') - - def _GetNamespacesInfoForScript(self, script, closurized_namespaces=None): - _, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - script, closurized_namespaces) - - return namespaces_info - - def _GetStartTokenAndNamespacesInfoForScript( - self, script, closurized_namespaces): - - token = testutil.TokenizeSource(script) - return token, self._GetInitializedNamespacesInfo( - token, closurized_namespaces, []) - - def _GetInitializedNamespacesInfo(self, token, closurized_namespaces, - ignored_extra_namespaces): - """Returns a namespaces info initialized with the given token stream.""" - namespaces_info = closurizednamespacesinfo.ClosurizedNamespacesInfo( - closurized_namespaces=closurized_namespaces, - ignored_extra_namespaces=ignored_extra_namespaces) - state_tracker = javascriptstatetracker.JavaScriptStateTracker() - - ecma_pass = ecmametadatapass.EcmaMetaDataPass() - ecma_pass.Process(token) - - state_tracker.DocFlagPass(token, error_handler=None) - - alias_pass = aliaspass.AliasPass(closurized_namespaces) - alias_pass.Process(token) - - while token: - state_tracker.HandleToken(token, state_tracker.GetLastNonSpaceToken()) - namespaces_info.ProcessToken(token, state_tracker) - state_tracker.HandleAfterToken(token) - token = token.next - - return namespaces_info - - def _GetProvideTokens(self, namespace): - """Returns a list of tokens for a goog.require of the given namespace.""" - line_text = 'goog.require(\'' + namespace + '\');\n' - return testutil.TokenizeSource([line_text]) - - def _GetRequireTokens(self, namespace): - """Returns a list of tokens for a goog.require of the given namespace.""" - line_text = 'goog.require(\'' + namespace + '\');\n' - return testutil.TokenizeSource([line_text]) - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/common/__init__.py b/tools/closure_linter/build/lib/closure_linter/common/__init__.py deleted file mode 100644 index 57930436ce4323..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Package indicator for gjslint.common.""" diff --git a/tools/closure_linter/build/lib/closure_linter/common/error.py b/tools/closure_linter/build/lib/closure_linter/common/error.py deleted file mode 100644 index 4209c235b85425..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/error.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Error object commonly used in linters.""" - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)') - - -class Error(object): - """Object representing a style error.""" - - def __init__(self, code, message, token=None, position=None, fix_data=None): - """Initialize the error object. - - Args: - code: The numeric error code. - message: The error message string. - token: The tokens.Token where the error occurred. - position: The position of the error within the token. - fix_data: Data to be used in autofixing. Codes with fix_data are: - GOOG_REQUIRES_NOT_ALPHABETIZED - List of string value tokens that are - class names in goog.requires calls. - """ - self.code = code - self.message = message - self.token = token - self.position = position - if token: - self.start_index = token.start_index - else: - self.start_index = 0 - self.fix_data = fix_data - if self.position: - self.start_index += self.position.start - - def Compare(a, b): - """Compare two error objects, by source code order. - - Args: - a: First error object. - b: Second error object. - - Returns: - A Negative/0/Positive number when a is before/the same as/after b. - """ - line_diff = a.token.line_number - b.token.line_number - if line_diff: - return line_diff - - return a.start_index - b.start_index - Compare = staticmethod(Compare) diff --git a/tools/closure_linter/build/lib/closure_linter/common/erroraccumulator.py b/tools/closure_linter/build/lib/closure_linter/common/erroraccumulator.py deleted file mode 100644 index 55844ba60356fa..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/erroraccumulator.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Linter error handler class that accumulates an array of errors.""" - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)') - - -from closure_linter.common import errorhandler - - -class ErrorAccumulator(errorhandler.ErrorHandler): - """Error handler object that accumulates errors in a list.""" - - def __init__(self): - self._errors = [] - - def HandleError(self, error): - """Append the error to the list. - - Args: - error: The error object - """ - self._errors.append(error) - - def GetErrors(self): - """Returns the accumulated errors. - - Returns: - A sequence of errors. - """ - return self._errors diff --git a/tools/closure_linter/build/lib/closure_linter/common/errorhandler.py b/tools/closure_linter/build/lib/closure_linter/common/errorhandler.py deleted file mode 100644 index 764d54d84cb3c1..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/errorhandler.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Interface for a linter error handler. - -Error handlers aggregate a set of errors from multiple files and can optionally -perform some action based on the reported errors, for example, logging the error -or automatically fixing it. -""" - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)') - - -class ErrorHandler(object): - """Error handler interface.""" - - def __init__(self): - if self.__class__ == ErrorHandler: - raise NotImplementedError('class ErrorHandler is abstract') - - def HandleFile(self, filename, first_token): - """Notifies this ErrorHandler that subsequent errors are in filename. - - Args: - filename: The file being linted. - first_token: The first token of the file. - """ - - def HandleError(self, error): - """Append the error to the list. - - Args: - error: The error object - """ - - def FinishFile(self): - """Finishes handling the current file. - - Should be called after all errors in a file have been handled. - """ - - def GetErrors(self): - """Returns the accumulated errors. - - Returns: - A sequence of errors. - """ diff --git a/tools/closure_linter/build/lib/closure_linter/common/erroroutput.py b/tools/closure_linter/build/lib/closure_linter/common/erroroutput.py deleted file mode 100644 index 149738b5d4f173..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/erroroutput.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Utility functions to format errors.""" - - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)', - '[email protected] (Nathan Naze)') - - -def GetUnixErrorOutput(filename, error, new_error=False): - """Get a output line for an error in UNIX format.""" - - line = '' - - if error.token: - line = '%d' % error.token.line_number - - error_code = '%04d' % error.code - if new_error: - error_code = 'New Error ' + error_code - return '%s:%s:(%s) %s' % (filename, line, error_code, error.message) - - -def GetErrorOutput(error, new_error=False): - """Get a output line for an error in regular format.""" - - line = '' - if error.token: - line = 'Line %d, ' % error.token.line_number - - code = 'E:%04d' % error.code - - error_message = error.message - if new_error: - error_message = 'New Error ' + error_message - - return '%s%s: %s' % (line, code, error.message) diff --git a/tools/closure_linter/build/lib/closure_linter/common/filetestcase.py b/tools/closure_linter/build/lib/closure_linter/common/filetestcase.py deleted file mode 100644 index 7cd83cd1dcf58c..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/filetestcase.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Test case that runs a checker on a file, matching errors against annotations. - -Runs the given checker on the given file, accumulating all errors. The list -of errors is then matched against those annotated in the file. Based heavily -on devtools/javascript/gpylint/full_test.py. -""" - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)') - -import re - -import gflags as flags -import unittest as googletest -from closure_linter.common import erroraccumulator - - -class AnnotatedFileTestCase(googletest.TestCase): - """Test case to run a linter against a single file.""" - - # Matches an all caps letters + underscores error identifer - _MESSAGE = {'msg': '[A-Z][A-Z_]+'} - # Matches a //, followed by an optional line number with a +/-, followed by a - # list of message IDs. Used to extract expected messages from testdata files. - # TODO(robbyw): Generalize to use different commenting patterns. - _EXPECTED_RE = re.compile(r'\s*//\s*(?:(?P[+-]?[0-9]+):)?' - r'\s*(?P%(msg)s(?:,\s*%(msg)s)*)' % _MESSAGE) - - def __init__(self, filename, lint_callable, converter): - """Create a single file lint test case. - - Args: - filename: Filename to test. - lint_callable: Callable that lints a file. This is usually runner.Run(). - converter: Function taking an error string and returning an error code. - """ - - googletest.TestCase.__init__(self, 'runTest') - self._filename = filename - self._messages = [] - self._lint_callable = lint_callable - self._converter = converter - - def setUp(self): - flags.FLAGS.dot_on_next_line = True - - def tearDown(self): - flags.FLAGS.dot_on_next_line = False - - def shortDescription(self): - """Provides a description for the test.""" - return 'Run linter on %s' % self._filename - - def runTest(self): - """Runs the test.""" - try: - filename = self._filename - stream = open(filename) - except IOError as ex: - raise IOError('Could not find testdata resource for %s: %s' % - (self._filename, ex)) - - expected = self._GetExpectedMessages(stream) - got = self._ProcessFileAndGetMessages(filename) - self.assertEqual(expected, got) - - def _GetExpectedMessages(self, stream): - """Parse a file and get a sorted list of expected messages.""" - messages = [] - for i, line in enumerate(stream): - match = self._EXPECTED_RE.search(line) - if match: - line = match.group('line') - msg_ids = match.group('msgs') - if line is None: - line = i + 1 - elif line.startswith('+') or line.startswith('-'): - line = i + 1 + int(line) - else: - line = int(line) - for msg_id in msg_ids.split(','): - # Ignore a spurious message from the license preamble. - if msg_id != 'WITHOUT': - messages.append((line, self._converter(msg_id.strip()))) - stream.seek(0) - messages.sort() - return messages - - def _ProcessFileAndGetMessages(self, filename): - """Trap gjslint's output parse it to get messages added.""" - error_accumulator = erroraccumulator.ErrorAccumulator() - self._lint_callable(filename, error_accumulator) - - errors = error_accumulator.GetErrors() - - # Convert to expected tuple format. - - error_msgs = [(error.token.line_number, error.code) for error in errors] - error_msgs.sort() - return error_msgs diff --git a/tools/closure_linter/build/lib/closure_linter/common/htmlutil.py b/tools/closure_linter/build/lib/closure_linter/common/htmlutil.py deleted file mode 100644 index 26d44c5908353d..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/htmlutil.py +++ /dev/null @@ -1,170 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Utilities for dealing with HTML.""" - -__author__ = ('[email protected] (Robert Walker)') - -import cStringIO -import formatter -import htmllib -import HTMLParser -import re - - -class ScriptExtractor(htmllib.HTMLParser): - """Subclass of HTMLParser that extracts script contents from an HTML file. - - Also inserts appropriate blank lines so that line numbers in the extracted - code match the line numbers in the original HTML. - """ - - def __init__(self): - """Initialize a ScriptExtractor.""" - htmllib.HTMLParser.__init__(self, formatter.NullFormatter()) - self._in_script = False - self._text = '' - - def start_script(self, attrs): - """Internal handler for the start of a script tag. - - Args: - attrs: The attributes of the script tag, as a list of tuples. - """ - for attribute in attrs: - if attribute[0].lower() == 'src': - # Skip script tags with a src specified. - return - self._in_script = True - - def end_script(self): - """Internal handler for the end of a script tag.""" - self._in_script = False - - def handle_data(self, data): - """Internal handler for character data. - - Args: - data: The character data from the HTML file. - """ - if self._in_script: - # If the last line contains whitespace only, i.e. is just there to - # properly align a tag, strip the whitespace. - if data.rstrip(' \t') != data.rstrip(' \t\n\r\f'): - data = data.rstrip(' \t') - self._text += data - else: - self._AppendNewlines(data) - - def handle_comment(self, data): - """Internal handler for HTML comments. - - Args: - data: The text of the comment. - """ - self._AppendNewlines(data) - - def _AppendNewlines(self, data): - """Count the number of newlines in the given string and append them. - - This ensures line numbers are correct for reported errors. - - Args: - data: The data to count newlines in. - """ - # We append 'x' to both sides of the string to ensure that splitlines - # gives us an accurate count. - for i in xrange(len(('x' + data + 'x').splitlines()) - 1): - self._text += '\n' - - def GetScriptLines(self): - """Return the extracted script lines. - - Returns: - The extracted script lines as a list of strings. - """ - return self._text.splitlines() - - -def GetScriptLines(f): - """Extract script tag contents from the given HTML file. - - Args: - f: The HTML file. - - Returns: - Lines in the HTML file that are from script tags. - """ - extractor = ScriptExtractor() - - # The HTML parser chokes on text like Array.<!string>, so we patch - # that bug by replacing the < with < - escaping all text inside script - # tags would be better but it's a bit of a catch 22. - contents = f.read() - contents = re.sub(r'<([^\s\w/])', - lambda x: '<%s' % x.group(1), - contents) - - extractor.feed(contents) - extractor.close() - return extractor.GetScriptLines() - - -def StripTags(str): - """Returns the string with HTML tags stripped. - - Args: - str: An html string. - - Returns: - The html string with all tags stripped. If there was a parse error, returns - the text successfully parsed so far. - """ - # Brute force approach to stripping as much HTML as possible. If there is a - # parsing error, don't strip text before parse error position, and continue - # trying from there. - final_text = '' - finished = False - while not finished: - try: - strip = _HtmlStripper() - strip.feed(str) - strip.close() - str = strip.get_output() - final_text += str - finished = True - except HTMLParser.HTMLParseError, e: - final_text += str[:e.offset] - str = str[e.offset + 1:] - - return final_text - - -class _HtmlStripper(HTMLParser.HTMLParser): - """Simple class to strip tags from HTML. - - Does so by doing nothing when encountering tags, and appending character data - to a buffer when that is encountered. - """ - def __init__(self): - self.reset() - self.__output = cStringIO.StringIO() - - def handle_data(self, d): - self.__output.write(d) - - def get_output(self): - return self.__output.getvalue() diff --git a/tools/closure_linter/build/lib/closure_linter/common/lintrunner.py b/tools/closure_linter/build/lib/closure_linter/common/lintrunner.py deleted file mode 100644 index 07842c7bfeb36f..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/lintrunner.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Interface for a lint running wrapper.""" - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)') - - -class LintRunner(object): - """Interface for a lint running wrapper.""" - - def __init__(self): - if self.__class__ == LintRunner: - raise NotImplementedError('class LintRunner is abstract') - - def Run(self, filenames, error_handler): - """Run a linter on the given filenames. - - Args: - filenames: The filenames to check - error_handler: An ErrorHandler object - - Returns: - The error handler, which may have been used to collect error info. - """ diff --git a/tools/closure_linter/build/lib/closure_linter/common/matcher.py b/tools/closure_linter/build/lib/closure_linter/common/matcher.py deleted file mode 100644 index 9b4402c6718bc7..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/matcher.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Regular expression based JavaScript matcher classes.""" - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)') - -from closure_linter.common import position -from closure_linter.common import tokens - -# Shorthand -Token = tokens.Token -Position = position.Position - - -class Matcher(object): - """A token matcher. - - Specifies a pattern to match, the type of token it represents, what mode the - token changes to, and what mode the token applies to. - - Modes allow more advanced grammars to be incorporated, and are also necessary - to tokenize line by line. We can have different patterns apply to different - modes - i.e. looking for documentation while in comment mode. - - Attributes: - regex: The regular expression representing this matcher. - type: The type of token indicated by a successful match. - result_mode: The mode to move to after a successful match. - """ - - def __init__(self, regex, token_type, result_mode=None, line_start=False): - """Create a new matcher template. - - Args: - regex: The regular expression to match. - token_type: The type of token a successful match indicates. - result_mode: What mode to change to after a successful match. Defaults to - None, which means to not change the current mode. - line_start: Whether this matcher should only match string at the start - of a line. - """ - self.regex = regex - self.type = token_type - self.result_mode = result_mode - self.line_start = line_start diff --git a/tools/closure_linter/build/lib/closure_linter/common/position.py b/tools/closure_linter/build/lib/closure_linter/common/position.py deleted file mode 100644 index cebf17ef36277e..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/position.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Classes to represent positions within strings.""" - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)') - - -class Position(object): - """Object representing a segment of a string. - - Attributes: - start: The index in to the string where the segment starts. - length: The length of the string segment. - """ - - def __init__(self, start, length): - """Initialize the position object. - - Args: - start: The start index. - length: The number of characters to include. - """ - self.start = start - self.length = length - - def Get(self, string): - """Returns this range of the given string. - - Args: - string: The string to slice. - - Returns: - The string within the range specified by this object. - """ - return string[self.start:self.start + self.length] - - def Set(self, target, source): - """Sets this range within the target string to the source string. - - Args: - target: The target string. - source: The source string. - - Returns: - The resulting string - """ - return target[:self.start] + source + target[self.start + self.length:] - - def AtEnd(string): - """Create a Position representing the end of the given string. - - Args: - string: The string to represent the end of. - - Returns: - The created Position object. - """ - return Position(len(string), 0) - AtEnd = staticmethod(AtEnd) - - def IsAtEnd(self, string): - """Returns whether this position is at the end of the given string. - - Args: - string: The string to test for the end of. - - Returns: - Whether this position is at the end of the given string. - """ - return self.start == len(string) and self.length == 0 - - def AtBeginning(): - """Create a Position representing the beginning of any string. - - Returns: - The created Position object. - """ - return Position(0, 0) - AtBeginning = staticmethod(AtBeginning) - - def IsAtBeginning(self): - """Returns whether this position is at the beginning of any string. - - Returns: - Whether this position is at the beginning of any string. - """ - return self.start == 0 and self.length == 0 - - def All(string): - """Create a Position representing the entire string. - - Args: - string: The string to represent the entirety of. - - Returns: - The created Position object. - """ - return Position(0, len(string)) - All = staticmethod(All) - - def Index(index): - """Returns a Position object for the specified index. - - Args: - index: The index to select, inclusively. - - Returns: - The created Position object. - """ - return Position(index, 1) - Index = staticmethod(Index) diff --git a/tools/closure_linter/build/lib/closure_linter/common/simplefileflags.py b/tools/closure_linter/build/lib/closure_linter/common/simplefileflags.py deleted file mode 100644 index 3402bef3a1d36e..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/simplefileflags.py +++ /dev/null @@ -1,190 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Determines the list of files to be checked from command line arguments.""" - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)') - -import glob -import os -import re - -import gflags as flags - - -FLAGS = flags.FLAGS - -flags.DEFINE_multistring( - 'recurse', - None, - 'Recurse in to the subdirectories of the given path', - short_name='r') -flags.DEFINE_list( - 'exclude_directories', - ('_demos'), - 'Exclude the specified directories (only applicable along with -r or ' - '--presubmit)', - short_name='e') -flags.DEFINE_list( - 'exclude_files', - ('deps.js'), - 'Exclude the specified files', - short_name='x') - - -def MatchesSuffixes(filename, suffixes): - """Returns whether the given filename matches one of the given suffixes. - - Args: - filename: Filename to check. - suffixes: Sequence of suffixes to check. - - Returns: - Whether the given filename matches one of the given suffixes. - """ - suffix = filename[filename.rfind('.'):] - return suffix in suffixes - - -def _GetUserSpecifiedFiles(argv, suffixes): - """Returns files to be linted, specified directly on the command line. - - Can handle the '*' wildcard in filenames, but no other wildcards. - - Args: - argv: Sequence of command line arguments. The second and following arguments - are assumed to be files that should be linted. - suffixes: Expected suffixes for the file type being checked. - - Returns: - A sequence of files to be linted. - """ - files = argv[1:] or [] - all_files = [] - lint_files = [] - - # Perform any necessary globs. - for f in files: - if f.find('*') != -1: - for result in glob.glob(f): - all_files.append(result) - else: - all_files.append(f) - - for f in all_files: - if MatchesSuffixes(f, suffixes): - lint_files.append(f) - return lint_files - - -def _GetRecursiveFiles(suffixes): - """Returns files to be checked specified by the --recurse flag. - - Args: - suffixes: Expected suffixes for the file type being checked. - - Returns: - A list of files to be checked. - """ - lint_files = [] - # Perform any request recursion - if FLAGS.recurse: - for start in FLAGS.recurse: - for root, subdirs, files in os.walk(start): - for f in files: - if MatchesSuffixes(f, suffixes): - lint_files.append(os.path.join(root, f)) - return lint_files - - -def GetAllSpecifiedFiles(argv, suffixes): - """Returns all files specified by the user on the commandline. - - Args: - argv: Sequence of command line arguments. The second and following arguments - are assumed to be files that should be linted. - suffixes: Expected suffixes for the file type - - Returns: - A list of all files specified directly or indirectly (via flags) on the - command line by the user. - """ - files = _GetUserSpecifiedFiles(argv, suffixes) - - if FLAGS.recurse: - files += _GetRecursiveFiles(suffixes) - - return FilterFiles(files) - - -def FilterFiles(files): - """Filters the list of files to be linted be removing any excluded files. - - Filters out files excluded using --exclude_files and --exclude_directories. - - Args: - files: Sequence of files that needs filtering. - - Returns: - Filtered list of files to be linted. - """ - num_files = len(files) - - ignore_dirs_regexs = [] - for ignore in FLAGS.exclude_directories: - ignore_dirs_regexs.append(re.compile(r'(^|[\\/])%s[\\/]' % ignore)) - - result_files = [] - for f in files: - add_file = True - for exclude in FLAGS.exclude_files: - if f.endswith('/' + exclude) or f == exclude: - add_file = False - break - for ignore in ignore_dirs_regexs: - if ignore.search(f): - # Break out of ignore loop so we don't add to - # filtered files. - add_file = False - break - if add_file: - # Convert everything to absolute paths so we can easily remove duplicates - # using a set. - result_files.append(os.path.abspath(f)) - - skipped = num_files - len(result_files) - if skipped: - print 'Skipping %d file(s).' % skipped - - return set(result_files) - - -def GetFileList(argv, file_type, suffixes): - """Parse the flags and return the list of files to check. - - Args: - argv: Sequence of command line arguments. - suffixes: Sequence of acceptable suffixes for the file type. - - Returns: - The list of files to check. - """ - return sorted(GetAllSpecifiedFiles(argv, suffixes)) - - -def IsEmptyArgumentList(argv): - return not (len(argv[1:]) or FLAGS.recurse) diff --git a/tools/closure_linter/build/lib/closure_linter/common/tokenizer.py b/tools/closure_linter/build/lib/closure_linter/common/tokenizer.py deleted file mode 100644 index 9420ea3267a5a2..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/tokenizer.py +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Regular expression based lexer.""" - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)') - -from closure_linter.common import tokens - -# Shorthand -Type = tokens.TokenType - - -class Tokenizer(object): - """General purpose tokenizer. - - Attributes: - mode: The latest mode of the tokenizer. This allows patterns to distinguish - if they are mid-comment, mid-parameter list, etc. - matchers: Dictionary of modes to sequences of matchers that define the - patterns to check at any given time. - default_types: Dictionary of modes to types, defining what type to give - non-matched text when in the given mode. Defaults to Type.NORMAL. - """ - - def __init__(self, starting_mode, matchers, default_types): - """Initialize the tokenizer. - - Args: - starting_mode: Mode to start in. - matchers: Dictionary of modes to sequences of matchers that defines the - patterns to check at any given time. - default_types: Dictionary of modes to types, defining what type to give - non-matched text when in the given mode. Defaults to Type.NORMAL. - """ - self.__starting_mode = starting_mode - self.matchers = matchers - self.default_types = default_types - - def TokenizeFile(self, file): - """Tokenizes the given file. - - Args: - file: An iterable that yields one line of the file at a time. - - Returns: - The first token in the file - """ - # The current mode. - self.mode = self.__starting_mode - # The first token in the stream. - self.__first_token = None - # The last token added to the token stream. - self.__last_token = None - # The current line number. - self.__line_number = 0 - - for line in file: - self.__line_number += 1 - self.__TokenizeLine(line) - - return self.__first_token - - def _CreateToken(self, string, token_type, line, line_number, values=None): - """Creates a new Token object (or subclass). - - Args: - string: The string of input the token represents. - token_type: The type of token. - line: The text of the line this token is in. - line_number: The line number of the token. - values: A dict of named values within the token. For instance, a - function declaration may have a value called 'name' which captures the - name of the function. - - Returns: - The newly created Token object. - """ - return tokens.Token(string, token_type, line, line_number, values, - line_number) - - def __TokenizeLine(self, line): - """Tokenizes the given line. - - Args: - line: The contents of the line. - """ - string = line.rstrip('\n\r\f') - line_number = self.__line_number - self.__start_index = 0 - - if not string: - self.__AddToken(self._CreateToken('', Type.BLANK_LINE, line, line_number)) - return - - normal_token = '' - index = 0 - while index < len(string): - for matcher in self.matchers[self.mode]: - if matcher.line_start and index > 0: - continue - - match = matcher.regex.match(string, index) - - if match: - if normal_token: - self.__AddToken( - self.__CreateNormalToken(self.mode, normal_token, line, - line_number)) - normal_token = '' - - # Add the match. - self.__AddToken(self._CreateToken(match.group(), matcher.type, line, - line_number, match.groupdict())) - - # Change the mode to the correct one for after this match. - self.mode = matcher.result_mode or self.mode - - # Shorten the string to be matched. - index = match.end() - - break - - else: - # If the for loop finishes naturally (i.e. no matches) we just add the - # first character to the string of consecutive non match characters. - # These will constitute a NORMAL token. - if string: - normal_token += string[index:index + 1] - index += 1 - - if normal_token: - self.__AddToken( - self.__CreateNormalToken(self.mode, normal_token, line, line_number)) - - def __CreateNormalToken(self, mode, string, line, line_number): - """Creates a normal token. - - Args: - mode: The current mode. - string: The string to tokenize. - line: The line of text. - line_number: The line number within the file. - - Returns: - A Token object, of the default type for the current mode. - """ - type = Type.NORMAL - if mode in self.default_types: - type = self.default_types[mode] - return self._CreateToken(string, type, line, line_number) - - def __AddToken(self, token): - """Add the given token to the token stream. - - Args: - token: The token to add. - """ - # Store the first token, or point the previous token to this one. - if not self.__first_token: - self.__first_token = token - else: - self.__last_token.next = token - - # Establish the doubly linked list - token.previous = self.__last_token - self.__last_token = token - - # Compute the character indices - token.start_index = self.__start_index - self.__start_index += token.length diff --git a/tools/closure_linter/build/lib/closure_linter/common/tokens.py b/tools/closure_linter/build/lib/closure_linter/common/tokens.py deleted file mode 100644 index 4703998752b036..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/tokens.py +++ /dev/null @@ -1,145 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Classes to represent tokens and positions within them.""" - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)') - - -class TokenType(object): - """Token types common to all languages.""" - NORMAL = 'normal' - WHITESPACE = 'whitespace' - BLANK_LINE = 'blank line' - - -class Token(object): - """Token class for intelligent text splitting. - - The token class represents a string of characters and an identifying type. - - Attributes: - type: The type of token. - string: The characters the token comprises. - length: The length of the token. - line: The text of the line the token is found in. - line_number: The number of the line the token is found in. - values: Dictionary of values returned from the tokens regex match. - previous: The token before this one. - next: The token after this one. - start_index: The character index in the line where this token starts. - attached_object: Object containing more information about this token. - metadata: Object containing metadata about this token. Must be added by - a separate metadata pass. - """ - - def __init__(self, string, token_type, line, line_number, values=None, - orig_line_number=None): - """Creates a new Token object. - - Args: - string: The string of input the token contains. - token_type: The type of token. - line: The text of the line this token is in. - line_number: The line number of the token. - values: A dict of named values within the token. For instance, a - function declaration may have a value called 'name' which captures the - name of the function. - orig_line_number: The line number of the original file this token comes - from. This should be only set during the tokenization process. For newly - created error fix tokens after that, it should be None. - """ - self.type = token_type - self.string = string - self.length = len(string) - self.line = line - self.line_number = line_number - self.orig_line_number = orig_line_number - self.values = values - self.is_deleted = False - - # These parts can only be computed when the file is fully tokenized - self.previous = None - self.next = None - self.start_index = None - - # This part is set in statetracker.py - # TODO(robbyw): Wrap this in to metadata - self.attached_object = None - - # This part is set in *metadatapass.py - self.metadata = None - - def IsFirstInLine(self): - """Tests if this token is the first token in its line. - - Returns: - Whether the token is the first token in its line. - """ - return not self.previous or self.previous.line_number != self.line_number - - def IsLastInLine(self): - """Tests if this token is the last token in its line. - - Returns: - Whether the token is the last token in its line. - """ - return not self.next or self.next.line_number != self.line_number - - def IsType(self, token_type): - """Tests if this token is of the given type. - - Args: - token_type: The type to test for. - - Returns: - True if the type of this token matches the type passed in. - """ - return self.type == token_type - - def IsAnyType(self, *token_types): - """Tests if this token is any of the given types. - - Args: - token_types: The types to check. Also accepts a single array. - - Returns: - True if the type of this token is any of the types passed in. - """ - if not isinstance(token_types[0], basestring): - return self.type in token_types[0] - else: - return self.type in token_types - - def __repr__(self): - return '' % (self.type, self.string, - self.values, self.line_number, - self.metadata) - - def __iter__(self): - """Returns a token iterator.""" - node = self - while node: - yield node - node = node.next - - def __reversed__(self): - """Returns a reverse-direction token iterator.""" - node = self - while node: - yield node - node = node.previous diff --git a/tools/closure_linter/build/lib/closure_linter/common/tokens_test.py b/tools/closure_linter/build/lib/closure_linter/common/tokens_test.py deleted file mode 100644 index 01ec89d01bc357..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/tokens_test.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# Copyright 2011 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - - -__author__ = '[email protected] (Nathan Naze)' - -import unittest as googletest -from closure_linter.common import tokens - - -def _CreateDummyToken(): - return tokens.Token('foo', None, 1, 1) - - -def _CreateDummyTokens(count): - dummy_tokens = [] - for _ in xrange(count): - dummy_tokens.append(_CreateDummyToken()) - return dummy_tokens - - -def _SetTokensAsNeighbors(neighbor_tokens): - for i in xrange(len(neighbor_tokens)): - prev_index = i - 1 - next_index = i + 1 - - if prev_index >= 0: - neighbor_tokens[i].previous = neighbor_tokens[prev_index] - - if next_index < len(neighbor_tokens): - neighbor_tokens[i].next = neighbor_tokens[next_index] - - -class TokensTest(googletest.TestCase): - - def testIsFirstInLine(self): - - # First token in file (has no previous). - self.assertTrue(_CreateDummyToken().IsFirstInLine()) - - a, b = _CreateDummyTokens(2) - _SetTokensAsNeighbors([a, b]) - - # Tokens on same line - a.line_number = 30 - b.line_number = 30 - - self.assertFalse(b.IsFirstInLine()) - - # Tokens on different lines - b.line_number = 31 - self.assertTrue(b.IsFirstInLine()) - - def testIsLastInLine(self): - # Last token in file (has no next). - self.assertTrue(_CreateDummyToken().IsLastInLine()) - - a, b = _CreateDummyTokens(2) - _SetTokensAsNeighbors([a, b]) - - # Tokens on same line - a.line_number = 30 - b.line_number = 30 - self.assertFalse(a.IsLastInLine()) - - b.line_number = 31 - self.assertTrue(a.IsLastInLine()) - - def testIsType(self): - a = tokens.Token('foo', 'fakeType1', 1, 1) - self.assertTrue(a.IsType('fakeType1')) - self.assertFalse(a.IsType('fakeType2')) - - def testIsAnyType(self): - a = tokens.Token('foo', 'fakeType1', 1, 1) - self.assertTrue(a.IsAnyType(['fakeType1', 'fakeType2'])) - self.assertFalse(a.IsAnyType(['fakeType3', 'fakeType4'])) - - def testRepr(self): - a = tokens.Token('foo', 'fakeType1', 1, 1) - self.assertEquals('', str(a)) - - def testIter(self): - dummy_tokens = _CreateDummyTokens(5) - _SetTokensAsNeighbors(dummy_tokens) - a, b, c, d, e = dummy_tokens - - i = iter(a) - self.assertListEqual([a, b, c, d, e], list(i)) - - def testReverseIter(self): - dummy_tokens = _CreateDummyTokens(5) - _SetTokensAsNeighbors(dummy_tokens) - a, b, c, d, e = dummy_tokens - - ri = reversed(e) - self.assertListEqual([e, d, c, b, a], list(ri)) - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/ecmalintrules.py b/tools/closure_linter/build/lib/closure_linter/ecmalintrules.py deleted file mode 100644 index c07dffc86eeae3..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/ecmalintrules.py +++ /dev/null @@ -1,844 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Core methods for checking EcmaScript files for common style guide violations. -""" - -__author__ = ('[email protected] (Robert Walker)', - '[email protected] (Andy Perelson)', - '[email protected] (Jacob Richman)') - -import re - -import gflags as flags - -from closure_linter import checkerbase -from closure_linter import ecmametadatapass -from closure_linter import error_check -from closure_linter import errorrules -from closure_linter import errors -from closure_linter import indentation -from closure_linter import javascripttokenizer -from closure_linter import javascripttokens -from closure_linter import statetracker -from closure_linter import tokenutil -from closure_linter.common import error -from closure_linter.common import position - - -FLAGS = flags.FLAGS -flags.DEFINE_list('custom_jsdoc_tags', '', 'Extra jsdoc tags to allow') -# TODO(user): When flipping this to True, remove logic from unit tests -# that overrides this flag. -flags.DEFINE_boolean('dot_on_next_line', False, 'Require dots to be' - 'placed on the next line for wrapped expressions') - -# TODO(robbyw): Check for extra parens on return statements -# TODO(robbyw): Check for 0px in strings -# TODO(robbyw): Ensure inline jsDoc is in {} -# TODO(robbyw): Check for valid JS types in parameter docs - -# Shorthand -Context = ecmametadatapass.EcmaContext -Error = error.Error -Modes = javascripttokenizer.JavaScriptModes -Position = position.Position -Rule = error_check.Rule -Type = javascripttokens.JavaScriptTokenType - - -class EcmaScriptLintRules(checkerbase.LintRulesBase): - """EmcaScript lint style checking rules. - - Can be used to find common style errors in JavaScript, ActionScript and other - Ecma like scripting languages. Style checkers for Ecma scripting languages - should inherit from this style checker. - Please do not add any state to EcmaScriptLintRules or to any subclasses. - - All state should be added to the StateTracker subclass used for a particular - language. - """ - - # It will be initialized in constructor so the flags are initialized. - max_line_length = -1 - - # Static constants. - MISSING_PARAMETER_SPACE = re.compile(r',\S') - - EXTRA_SPACE = re.compile(r'(\(\s|\s\))') - - ENDS_WITH_SPACE = re.compile(r'\s$') - - ILLEGAL_TAB = re.compile(r'\t') - - # Regex used to split up complex types to check for invalid use of ? and |. - TYPE_SPLIT = re.compile(r'[,<>()]') - - # Regex for form of author lines after the @author tag. - AUTHOR_SPEC = re.compile(r'(\s*)[^\s]+@[^(\s]+(\s*)\(.+\)') - - # Acceptable tokens to remove for line too long testing. - LONG_LINE_IGNORE = frozenset( - ['*', '//', '@see'] + - ['@%s' % tag for tag in statetracker.DocFlag.HAS_TYPE]) - - JSDOC_FLAGS_DESCRIPTION_NOT_REQUIRED = frozenset([ - '@fileoverview', '@param', '@return', '@returns']) - - def __init__(self): - """Initialize this lint rule object.""" - checkerbase.LintRulesBase.__init__(self) - if EcmaScriptLintRules.max_line_length == -1: - EcmaScriptLintRules.max_line_length = errorrules.GetMaxLineLength() - - def Initialize(self, checker, limited_doc_checks, is_html): - """Initialize this lint rule object before parsing a new file.""" - checkerbase.LintRulesBase.Initialize(self, checker, limited_doc_checks, - is_html) - self._indentation = indentation.IndentationRules() - - def HandleMissingParameterDoc(self, token, param_name): - """Handle errors associated with a parameter missing a @param tag.""" - raise TypeError('Abstract method HandleMissingParameterDoc not implemented') - - def _CheckLineLength(self, last_token, state): - """Checks whether the line is too long. - - Args: - last_token: The last token in the line. - state: parser_state object that indicates the current state in the page - """ - # Start from the last token so that we have the flag object attached to - # and DOC_FLAG tokens. - line_number = last_token.line_number - token = last_token - - # Build a representation of the string where spaces indicate potential - # line-break locations. - line = [] - while token and token.line_number == line_number: - if state.IsTypeToken(token): - line.insert(0, 'x' * len(token.string)) - elif token.type in (Type.IDENTIFIER, Type.OPERATOR): - # Dots are acceptable places to wrap (may be tokenized as identifiers). - line.insert(0, token.string.replace('.', ' ')) - else: - line.insert(0, token.string) - token = token.previous - - line = ''.join(line) - line = line.rstrip('\n\r\f') - try: - length = len(unicode(line, 'utf-8')) - except (LookupError, UnicodeDecodeError): - # Unknown encoding. The line length may be wrong, as was originally the - # case for utf-8 (see bug 1735846). For now just accept the default - # length, but as we find problems we can either add test for other - # possible encodings or return without an error to protect against - # false positives at the cost of more false negatives. - length = len(line) - - if length > EcmaScriptLintRules.max_line_length: - - # If the line matches one of the exceptions, then it's ok. - for long_line_regexp in self.GetLongLineExceptions(): - if long_line_regexp.match(last_token.line): - return - - # If the line consists of only one "word", or multiple words but all - # except one are ignoreable, then it's ok. - parts = set(line.split()) - - # We allow two "words" (type and name) when the line contains @param - max_parts = 1 - if '@param' in parts: - max_parts = 2 - - # Custom tags like @requires may have url like descriptions, so ignore - # the tag, similar to how we handle @see. - custom_tags = set(['@%s' % f for f in FLAGS.custom_jsdoc_tags]) - if (len(parts.difference(self.LONG_LINE_IGNORE | custom_tags)) - > max_parts): - self._HandleError( - errors.LINE_TOO_LONG, - 'Line too long (%d characters).' % len(line), last_token) - - def _CheckJsDocType(self, token, js_type): - """Checks the given type for style errors. - - Args: - token: The DOC_FLAG token for the flag whose type to check. - js_type: The flag's typeannotation.TypeAnnotation instance. - """ - if not js_type: return - - if js_type.type_group and len(js_type.sub_types) == 2: - identifiers = [t.identifier for t in js_type.sub_types] - if 'null' in identifiers: - # Don't warn if the identifier is a template type (e.g. {TYPE|null}. - if not identifiers[0].isupper() and not identifiers[1].isupper(): - self._HandleError( - errors.JSDOC_PREFER_QUESTION_TO_PIPE_NULL, - 'Prefer "?Type" to "Type|null": "%s"' % js_type, token) - - # TODO(user): We should report an error for wrong usage of '?' and '|' - # e.g. {?number|string|null} etc. - - for sub_type in js_type.IterTypes(): - self._CheckJsDocType(token, sub_type) - - def _CheckForMissingSpaceBeforeToken(self, token): - """Checks for a missing space at the beginning of a token. - - Reports a MISSING_SPACE error if the token does not begin with a space or - the previous token doesn't end with a space and the previous token is on the - same line as the token. - - Args: - token: The token being checked - """ - # TODO(user): Check if too many spaces? - if (len(token.string) == len(token.string.lstrip()) and - token.previous and token.line_number == token.previous.line_number and - len(token.previous.string) - len(token.previous.string.rstrip()) == 0): - self._HandleError( - errors.MISSING_SPACE, - 'Missing space before "%s"' % token.string, - token, - position=Position.AtBeginning()) - - def _CheckOperator(self, token): - """Checks an operator for spacing and line style. - - Args: - token: The operator token. - """ - last_code = token.metadata.last_code - - if not self._ExpectSpaceBeforeOperator(token): - if (token.previous and token.previous.type == Type.WHITESPACE and - last_code and last_code.type in (Type.NORMAL, Type.IDENTIFIER) and - last_code.line_number == token.line_number): - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before "%s"' % token.string, - token.previous, position=Position.All(token.previous.string)) - - elif (token.previous and - not token.previous.IsComment() and - not tokenutil.IsDot(token) and - token.previous.type in Type.EXPRESSION_ENDER_TYPES): - self._HandleError(errors.MISSING_SPACE, - 'Missing space before "%s"' % token.string, token, - position=Position.AtBeginning()) - - # Check wrapping of operators. - next_code = tokenutil.GetNextCodeToken(token) - - is_dot = tokenutil.IsDot(token) - wrapped_before = last_code and last_code.line_number != token.line_number - wrapped_after = next_code and next_code.line_number != token.line_number - - if FLAGS.dot_on_next_line and is_dot and wrapped_after: - self._HandleError( - errors.LINE_ENDS_WITH_DOT, - '"." must go on the following line', - token) - if (not is_dot and wrapped_before and - not token.metadata.IsUnaryOperator()): - self._HandleError( - errors.LINE_STARTS_WITH_OPERATOR, - 'Binary operator must go on previous line "%s"' % token.string, - token) - - def _IsLabel(self, token): - # A ':' token is considered part of a label if it occurs in a case - # statement, a plain label, or an object literal, i.e. is not part of a - # ternary. - - return (token.string == ':' and - token.metadata.context.type in (Context.LITERAL_ELEMENT, - Context.CASE_BLOCK, - Context.STATEMENT)) - - def _ExpectSpaceBeforeOperator(self, token): - """Returns whether a space should appear before the given operator token. - - Args: - token: The operator token. - - Returns: - Whether there should be a space before the token. - """ - if token.string == ',' or token.metadata.IsUnaryPostOperator(): - return False - - if tokenutil.IsDot(token): - return False - - # Colons should appear in labels, object literals, the case of a switch - # statement, and ternary operator. Only want a space in the case of the - # ternary operator. - if self._IsLabel(token): - return False - - if token.metadata.IsUnaryOperator() and token.IsFirstInLine(): - return False - - return True - - def CheckToken(self, token, state): - """Checks a token, given the current parser_state, for warnings and errors. - - Args: - token: The current token under consideration - state: parser_state object that indicates the current state in the page - """ - # Store some convenience variables - first_in_line = token.IsFirstInLine() - last_in_line = token.IsLastInLine() - last_non_space_token = state.GetLastNonSpaceToken() - - token_type = token.type - - # Process the line change. - if not self._is_html and error_check.ShouldCheck(Rule.INDENTATION): - # TODO(robbyw): Support checking indentation in HTML files. - indentation_errors = self._indentation.CheckToken(token, state) - for indentation_error in indentation_errors: - self._HandleError(*indentation_error) - - if last_in_line: - self._CheckLineLength(token, state) - - if token_type == Type.PARAMETERS: - # Find missing spaces in parameter lists. - if self.MISSING_PARAMETER_SPACE.search(token.string): - fix_data = ', '.join([s.strip() for s in token.string.split(',')]) - self._HandleError(errors.MISSING_SPACE, 'Missing space after ","', - token, position=None, fix_data=fix_data.strip()) - - # Find extra spaces at the beginning of parameter lists. Make sure - # we aren't at the beginning of a continuing multi-line list. - if not first_in_line: - space_count = len(token.string) - len(token.string.lstrip()) - if space_count: - self._HandleError(errors.EXTRA_SPACE, 'Extra space after "("', - token, position=Position(0, space_count)) - - elif (token_type == Type.START_BLOCK and - token.metadata.context.type == Context.BLOCK): - self._CheckForMissingSpaceBeforeToken(token) - - elif token_type == Type.END_BLOCK: - last_code = token.metadata.last_code - if state.InFunction() and state.IsFunctionClose(): - if state.InTopLevelFunction(): - # A semicolons should not be included at the end of a function - # declaration. - if not state.InAssignedFunction(): - if not last_in_line and token.next.type == Type.SEMICOLON: - self._HandleError( - errors.ILLEGAL_SEMICOLON_AFTER_FUNCTION, - 'Illegal semicolon after function declaration', - token.next, position=Position.All(token.next.string)) - - # A semicolon should be included at the end of a function expression - # that is not immediately called or used by a dot operator. - if (state.InAssignedFunction() and token.next - and token.next.type != Type.SEMICOLON): - next_token = tokenutil.GetNextCodeToken(token) - is_immediately_used = (next_token.type == Type.START_PAREN or - tokenutil.IsDot(next_token)) - if not is_immediately_used: - self._HandleError( - errors.MISSING_SEMICOLON_AFTER_FUNCTION, - 'Missing semicolon after function assigned to a variable', - token, position=Position.AtEnd(token.string)) - - if state.InInterfaceMethod() and last_code.type != Type.START_BLOCK: - self._HandleError(errors.INTERFACE_METHOD_CANNOT_HAVE_CODE, - 'Interface methods cannot contain code', last_code) - - elif (state.IsBlockClose() and - token.next and token.next.type == Type.SEMICOLON): - if (last_code.metadata.context.parent.type != Context.OBJECT_LITERAL - and last_code.metadata.context.type != Context.OBJECT_LITERAL): - self._HandleError( - errors.REDUNDANT_SEMICOLON, - 'No semicolon is required to end a code block', - token.next, position=Position.All(token.next.string)) - - elif token_type == Type.SEMICOLON: - if token.previous and token.previous.type == Type.WHITESPACE: - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before ";"', - token.previous, position=Position.All(token.previous.string)) - - if token.next and token.next.line_number == token.line_number: - if token.metadata.context.type != Context.FOR_GROUP_BLOCK: - # TODO(robbyw): Error about no multi-statement lines. - pass - - elif token.next.type not in ( - Type.WHITESPACE, Type.SEMICOLON, Type.END_PAREN): - self._HandleError( - errors.MISSING_SPACE, - 'Missing space after ";" in for statement', - token.next, - position=Position.AtBeginning()) - - last_code = token.metadata.last_code - if last_code and last_code.type == Type.SEMICOLON: - # Allow a single double semi colon in for loops for cases like: - # for (;;) { }. - # NOTE(user): This is not a perfect check, and will not throw an error - # for cases like: for (var i = 0;; i < n; i++) {}, but then your code - # probably won't work either. - for_token = tokenutil.CustomSearch( - last_code, - lambda token: token.type == Type.KEYWORD and token.string == 'for', - end_func=lambda token: token.type == Type.SEMICOLON, - distance=None, - reverse=True) - - if not for_token: - self._HandleError(errors.REDUNDANT_SEMICOLON, 'Redundant semicolon', - token, position=Position.All(token.string)) - - elif token_type == Type.START_PAREN: - # Ensure that opening parentheses have a space before any keyword - # that is not being invoked like a member function. - if (token.previous and token.previous.type == Type.KEYWORD and - (not token.previous.metadata or - not token.previous.metadata.last_code or - not token.previous.metadata.last_code.string or - token.previous.metadata.last_code.string[-1:] != '.')): - self._HandleError(errors.MISSING_SPACE, 'Missing space before "("', - token, position=Position.AtBeginning()) - elif token.previous and token.previous.type == Type.WHITESPACE: - before_space = token.previous.previous - # Ensure that there is no extra space before a function invocation, - # even if the function being invoked happens to be a keyword. - if (before_space and before_space.line_number == token.line_number and - before_space.type == Type.IDENTIFIER or - (before_space.type == Type.KEYWORD and before_space.metadata and - before_space.metadata.last_code and - before_space.metadata.last_code.string and - before_space.metadata.last_code.string[-1:] == '.')): - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before "("', - token.previous, position=Position.All(token.previous.string)) - - elif token_type == Type.START_BRACKET: - self._HandleStartBracket(token, last_non_space_token) - elif token_type in (Type.END_PAREN, Type.END_BRACKET): - # Ensure there is no space before closing parentheses, except when - # it's in a for statement with an omitted section, or when it's at the - # beginning of a line. - if (token.previous and token.previous.type == Type.WHITESPACE and - not token.previous.IsFirstInLine() and - not (last_non_space_token and last_non_space_token.line_number == - token.line_number and - last_non_space_token.type == Type.SEMICOLON)): - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before "%s"' % - token.string, token.previous, - position=Position.All(token.previous.string)) - - elif token_type == Type.WHITESPACE: - if self.ILLEGAL_TAB.search(token.string): - if token.IsFirstInLine(): - if token.next: - self._HandleError( - errors.ILLEGAL_TAB, - 'Illegal tab in whitespace before "%s"' % token.next.string, - token, position=Position.All(token.string)) - else: - self._HandleError( - errors.ILLEGAL_TAB, - 'Illegal tab in whitespace', - token, position=Position.All(token.string)) - else: - self._HandleError( - errors.ILLEGAL_TAB, - 'Illegal tab in whitespace after "%s"' % token.previous.string, - token, position=Position.All(token.string)) - - # Check whitespace length if it's not the first token of the line and - # if it's not immediately before a comment. - if last_in_line: - # Check for extra whitespace at the end of a line. - self._HandleError(errors.EXTRA_SPACE, 'Extra space at end of line', - token, position=Position.All(token.string)) - elif not first_in_line and not token.next.IsComment(): - if token.length > 1: - self._HandleError( - errors.EXTRA_SPACE, 'Extra space after "%s"' % - token.previous.string, token, - position=Position(1, len(token.string) - 1)) - - elif token_type == Type.OPERATOR: - self._CheckOperator(token) - elif token_type == Type.DOC_FLAG: - flag = token.attached_object - - if flag.flag_type == 'bug': - # TODO(robbyw): Check for exactly 1 space on the left. - string = token.next.string.lstrip() - string = string.split(' ', 1)[0] - - if not string.isdigit(): - self._HandleError(errors.NO_BUG_NUMBER_AFTER_BUG_TAG, - '@bug should be followed by a bug number', token) - - elif flag.flag_type == 'suppress': - if flag.type is None: - # A syntactically invalid suppress tag will get tokenized as a normal - # flag, indicating an error. - self._HandleError( - errors.INCORRECT_SUPPRESS_SYNTAX, - 'Invalid suppress syntax: should be @suppress {errortype}. ' - 'Spaces matter.', token) - else: - for suppress_type in flag.jstype.IterIdentifiers(): - if suppress_type not in state.GetDocFlag().SUPPRESS_TYPES: - self._HandleError( - errors.INVALID_SUPPRESS_TYPE, - 'Invalid suppression type: %s' % suppress_type, token) - - elif (error_check.ShouldCheck(Rule.WELL_FORMED_AUTHOR) and - flag.flag_type == 'author'): - # TODO(user): In non strict mode check the author tag for as much as - # it exists, though the full form checked below isn't required. - string = token.next.string - result = self.AUTHOR_SPEC.match(string) - if not result: - self._HandleError(errors.INVALID_AUTHOR_TAG_DESCRIPTION, - 'Author tag line should be of the form: ' - '@author [email protected] (Your Name)', - token.next) - else: - # Check spacing between email address and name. Do this before - # checking earlier spacing so positions are easier to calculate for - # autofixing. - num_spaces = len(result.group(2)) - if num_spaces < 1: - self._HandleError(errors.MISSING_SPACE, - 'Missing space after email address', - token.next, position=Position(result.start(2), 0)) - elif num_spaces > 1: - self._HandleError( - errors.EXTRA_SPACE, 'Extra space after email address', - token.next, - position=Position(result.start(2) + 1, num_spaces - 1)) - - # Check for extra spaces before email address. Can't be too few, if - # not at least one we wouldn't match @author tag. - num_spaces = len(result.group(1)) - if num_spaces > 1: - self._HandleError(errors.EXTRA_SPACE, - 'Extra space before email address', - token.next, position=Position(1, num_spaces - 1)) - - elif (flag.flag_type in state.GetDocFlag().HAS_DESCRIPTION and - not self._limited_doc_checks): - if flag.flag_type == 'param': - if flag.name is None: - self._HandleError(errors.MISSING_JSDOC_PARAM_NAME, - 'Missing name in @param tag', token) - - if not flag.description or flag.description is None: - flag_name = token.type - if 'name' in token.values: - flag_name = '@' + token.values['name'] - - if flag_name not in self.JSDOC_FLAGS_DESCRIPTION_NOT_REQUIRED: - self._HandleError( - errors.MISSING_JSDOC_TAG_DESCRIPTION, - 'Missing description in %s tag' % flag_name, token) - else: - self._CheckForMissingSpaceBeforeToken(flag.description_start_token) - - if flag.HasType(): - if flag.type_start_token is not None: - self._CheckForMissingSpaceBeforeToken( - token.attached_object.type_start_token) - - if flag.jstype and not flag.jstype.IsEmpty(): - self._CheckJsDocType(token, flag.jstype) - - if error_check.ShouldCheck(Rule.BRACES_AROUND_TYPE) and ( - flag.type_start_token.type != Type.DOC_START_BRACE or - flag.type_end_token.type != Type.DOC_END_BRACE): - self._HandleError( - errors.MISSING_BRACES_AROUND_TYPE, - 'Type must always be surrounded by curly braces.', token) - - if token_type in (Type.DOC_FLAG, Type.DOC_INLINE_FLAG): - if (token.values['name'] not in state.GetDocFlag().LEGAL_DOC and - token.values['name'] not in FLAGS.custom_jsdoc_tags): - self._HandleError( - errors.INVALID_JSDOC_TAG, - 'Invalid JsDoc tag: %s' % token.values['name'], token) - - if (error_check.ShouldCheck(Rule.NO_BRACES_AROUND_INHERIT_DOC) and - token.values['name'] == 'inheritDoc' and - token_type == Type.DOC_INLINE_FLAG): - self._HandleError(errors.UNNECESSARY_BRACES_AROUND_INHERIT_DOC, - 'Unnecessary braces around @inheritDoc', - token) - - elif token_type == Type.SIMPLE_LVALUE: - identifier = token.values['identifier'] - - if ((not state.InFunction() or state.InConstructor()) and - state.InTopLevel() and not state.InObjectLiteralDescendant()): - jsdoc = state.GetDocComment() - if not state.HasDocComment(identifier): - # Only test for documentation on identifiers with .s in them to - # avoid checking things like simple variables. We don't require - # documenting assignments to .prototype itself (bug 1880803). - if (not state.InConstructor() and - identifier.find('.') != -1 and not - identifier.endswith('.prototype') and not - self._limited_doc_checks): - comment = state.GetLastComment() - if not (comment and comment.lower().count('jsdoc inherited')): - self._HandleError( - errors.MISSING_MEMBER_DOCUMENTATION, - "No docs found for member '%s'" % identifier, - token) - elif jsdoc and (not state.InConstructor() or - identifier.startswith('this.')): - # We are at the top level and the function/member is documented. - if identifier.endswith('_') and not identifier.endswith('__'): - # Can have a private class which inherits documentation from a - # public superclass. - # - # @inheritDoc is deprecated in favor of using @override, and they - if (jsdoc.HasFlag('override') and not jsdoc.HasFlag('constructor') - and ('accessControls' not in jsdoc.suppressions)): - self._HandleError( - errors.INVALID_OVERRIDE_PRIVATE, - '%s should not override a private member.' % identifier, - jsdoc.GetFlag('override').flag_token) - if (jsdoc.HasFlag('inheritDoc') and not jsdoc.HasFlag('constructor') - and ('accessControls' not in jsdoc.suppressions)): - self._HandleError( - errors.INVALID_INHERIT_DOC_PRIVATE, - '%s should not inherit from a private member.' % identifier, - jsdoc.GetFlag('inheritDoc').flag_token) - if (not jsdoc.HasFlag('private') and - ('underscore' not in jsdoc.suppressions) and not - ((jsdoc.HasFlag('inheritDoc') or jsdoc.HasFlag('override')) and - ('accessControls' in jsdoc.suppressions))): - self._HandleError( - errors.MISSING_PRIVATE, - 'Member "%s" must have @private JsDoc.' % - identifier, token) - if jsdoc.HasFlag('private') and 'underscore' in jsdoc.suppressions: - self._HandleError( - errors.UNNECESSARY_SUPPRESS, - '@suppress {underscore} is not necessary with @private', - jsdoc.suppressions['underscore']) - elif (jsdoc.HasFlag('private') and - not self.InExplicitlyTypedLanguage()): - # It is convention to hide public fields in some ECMA - # implementations from documentation using the @private tag. - self._HandleError( - errors.EXTRA_PRIVATE, - 'Member "%s" must not have @private JsDoc' % - identifier, token) - - # These flags are only legal on localizable message definitions; - # such variables always begin with the prefix MSG_. - for f in ('desc', 'hidden', 'meaning'): - if (jsdoc.HasFlag(f) - and not identifier.startswith('MSG_') - and identifier.find('.MSG_') == -1): - self._HandleError( - errors.INVALID_USE_OF_DESC_TAG, - 'Member "%s" should not have @%s JsDoc' % (identifier, f), - token) - - # Check for illegaly assigning live objects as prototype property values. - index = identifier.find('.prototype.') - # Ignore anything with additional .s after the prototype. - if index != -1 and identifier.find('.', index + 11) == -1: - equal_operator = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) - next_code = tokenutil.SearchExcept(equal_operator, Type.NON_CODE_TYPES) - if next_code and ( - next_code.type in (Type.START_BRACKET, Type.START_BLOCK) or - next_code.IsOperator('new')): - self._HandleError( - errors.ILLEGAL_PROTOTYPE_MEMBER_VALUE, - 'Member %s cannot have a non-primitive value' % identifier, - token) - - elif token_type == Type.END_PARAMETERS: - # Find extra space at the end of parameter lists. We check the token - # prior to the current one when it is a closing paren. - if (token.previous and token.previous.type == Type.PARAMETERS - and self.ENDS_WITH_SPACE.search(token.previous.string)): - self._HandleError(errors.EXTRA_SPACE, 'Extra space before ")"', - token.previous) - - jsdoc = state.GetDocComment() - if state.GetFunction().is_interface: - if token.previous and token.previous.type == Type.PARAMETERS: - self._HandleError( - errors.INTERFACE_CONSTRUCTOR_CANNOT_HAVE_PARAMS, - 'Interface constructor cannot have parameters', - token.previous) - elif (state.InTopLevel() and jsdoc and not jsdoc.HasFlag('see') - and not jsdoc.InheritsDocumentation() - and not state.InObjectLiteralDescendant() and not - jsdoc.IsInvalidated()): - distance, edit = jsdoc.CompareParameters(state.GetParams()) - if distance: - params_iter = iter(state.GetParams()) - docs_iter = iter(jsdoc.ordered_params) - - for op in edit: - if op == 'I': - # Insertion. - # Parsing doc comments is the same for all languages - # but some languages care about parameters that don't have - # doc comments and some languages don't care. - # Languages that don't allow variables to by typed such as - # JavaScript care but languages such as ActionScript or Java - # that allow variables to be typed don't care. - if not self._limited_doc_checks: - self.HandleMissingParameterDoc(token, params_iter.next()) - - elif op == 'D': - # Deletion - self._HandleError(errors.EXTRA_PARAMETER_DOCUMENTATION, - 'Found docs for non-existing parameter: "%s"' % - docs_iter.next(), token) - elif op == 'S': - # Substitution - if not self._limited_doc_checks: - self._HandleError( - errors.WRONG_PARAMETER_DOCUMENTATION, - 'Parameter mismatch: got "%s", expected "%s"' % - (params_iter.next(), docs_iter.next()), token) - - else: - # Equality - just advance the iterators - params_iter.next() - docs_iter.next() - - elif token_type == Type.STRING_TEXT: - # If this is the first token after the start of the string, but it's at - # the end of a line, we know we have a multi-line string. - if token.previous.type in ( - Type.SINGLE_QUOTE_STRING_START, - Type.DOUBLE_QUOTE_STRING_START) and last_in_line: - self._HandleError(errors.MULTI_LINE_STRING, - 'Multi-line strings are not allowed', token) - - # This check is orthogonal to the ones above, and repeats some types, so - # it is a plain if and not an elif. - if token.type in Type.COMMENT_TYPES: - if self.ILLEGAL_TAB.search(token.string): - self._HandleError(errors.ILLEGAL_TAB, - 'Illegal tab in comment "%s"' % token.string, token) - - trimmed = token.string.rstrip() - if last_in_line and token.string != trimmed: - # Check for extra whitespace at the end of a line. - self._HandleError( - errors.EXTRA_SPACE, 'Extra space at end of line', token, - position=Position(len(trimmed), len(token.string) - len(trimmed))) - - # This check is also orthogonal since it is based on metadata. - if token.metadata.is_implied_semicolon: - self._HandleError(errors.MISSING_SEMICOLON, - 'Missing semicolon at end of line', token) - - def _HandleStartBracket(self, token, last_non_space_token): - """Handles a token that is an open bracket. - - Args: - token: The token to handle. - last_non_space_token: The last token that was not a space. - """ - if (not token.IsFirstInLine() and token.previous.type == Type.WHITESPACE and - last_non_space_token and - last_non_space_token.type in Type.EXPRESSION_ENDER_TYPES): - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before "["', - token.previous, position=Position.All(token.previous.string)) - # If the [ token is the first token in a line we shouldn't complain - # about a missing space before [. This is because some Ecma script - # languages allow syntax like: - # [Annotation] - # class MyClass {...} - # So we don't want to blindly warn about missing spaces before [. - # In the the future, when rules for computing exactly how many spaces - # lines should be indented are added, then we can return errors for - # [ tokens that are improperly indented. - # For example: - # var someVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongVariableName = - # [a,b,c]; - # should trigger a proper indentation warning message as [ is not indented - # by four spaces. - elif (not token.IsFirstInLine() and token.previous and - token.previous.type not in ( - [Type.WHITESPACE, Type.START_PAREN, Type.START_BRACKET] + - Type.EXPRESSION_ENDER_TYPES)): - self._HandleError(errors.MISSING_SPACE, 'Missing space before "["', - token, position=Position.AtBeginning()) - - def Finalize(self, state): - """Perform all checks that need to occur after all lines are processed. - - Args: - state: State of the parser after parsing all tokens - - Raises: - TypeError: If not overridden. - """ - last_non_space_token = state.GetLastNonSpaceToken() - # Check last line for ending with newline. - if state.GetLastLine() and not ( - state.GetLastLine().isspace() or - state.GetLastLine().rstrip('\n\r\f') != state.GetLastLine()): - self._HandleError( - errors.FILE_MISSING_NEWLINE, - 'File does not end with new line. (%s)' % state.GetLastLine(), - last_non_space_token) - - try: - self._indentation.Finalize() - except Exception, e: - self._HandleError( - errors.FILE_DOES_NOT_PARSE, - str(e), - last_non_space_token) - - def GetLongLineExceptions(self): - """Gets a list of regexps for lines which can be longer than the limit. - - Returns: - A list of regexps, used as matches (rather than searches). - """ - return [] - - def InExplicitlyTypedLanguage(self): - """Returns whether this ecma implementation is explicitly typed.""" - return False diff --git a/tools/closure_linter/build/lib/closure_linter/ecmametadatapass.py b/tools/closure_linter/build/lib/closure_linter/ecmametadatapass.py deleted file mode 100644 index 50621610efe08d..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/ecmametadatapass.py +++ /dev/null @@ -1,574 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2010 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""Metadata pass for annotating tokens in EcmaScript files.""" - -__author__ = ('[email protected] (Robert Walker)') - -from closure_linter import javascripttokens -from closure_linter import tokenutil - - -TokenType = javascripttokens.JavaScriptTokenType - - -class ParseError(Exception): - """Exception indicating a parse error at the given token. - - Attributes: - token: The token where the parse error occurred. - """ - - def __init__(self, token, message=None): - """Initialize a parse error at the given token with an optional message. - - Args: - token: The token where the parse error occurred. - message: A message describing the parse error. - """ - Exception.__init__(self, message) - self.token = token - - -class EcmaContext(object): - """Context object for EcmaScript languages. - - Attributes: - type: The context type. - start_token: The token where this context starts. - end_token: The token where this context ends. - parent: The parent context. - """ - - # The root context. - ROOT = 'root' - - # A block of code. - BLOCK = 'block' - - # A pseudo-block of code for a given case or default section. - CASE_BLOCK = 'case_block' - - # Block of statements in a for loop's parentheses. - FOR_GROUP_BLOCK = 'for_block' - - # An implied block of code for 1 line if, while, and for statements - IMPLIED_BLOCK = 'implied_block' - - # An index in to an array or object. - INDEX = 'index' - - # An array literal in []. - ARRAY_LITERAL = 'array_literal' - - # An object literal in {}. - OBJECT_LITERAL = 'object_literal' - - # An individual element in an array or object literal. - LITERAL_ELEMENT = 'literal_element' - - # The portion of a ternary statement between ? and : - TERNARY_TRUE = 'ternary_true' - - # The portion of a ternary statment after : - TERNARY_FALSE = 'ternary_false' - - # The entire switch statment. This will contain a GROUP with the variable - # and a BLOCK with the code. - - # Since that BLOCK is not a normal block, it can not contain statements except - # for case and default. - SWITCH = 'switch' - - # A normal comment. - COMMENT = 'comment' - - # A JsDoc comment. - DOC = 'doc' - - # An individual statement. - STATEMENT = 'statement' - - # Code within parentheses. - GROUP = 'group' - - # Parameter names in a function declaration. - PARAMETERS = 'parameters' - - # A set of variable declarations appearing after the 'var' keyword. - VAR = 'var' - - # Context types that are blocks. - BLOCK_TYPES = frozenset([ - ROOT, BLOCK, CASE_BLOCK, FOR_GROUP_BLOCK, IMPLIED_BLOCK]) - - def __init__(self, context_type, start_token, parent=None): - """Initializes the context object. - - Args: - context_type: The context type. - start_token: The token where this context starts. - parent: The parent context. - - Attributes: - type: The context type. - start_token: The token where this context starts. - end_token: The token where this context ends. - parent: The parent context. - children: The child contexts of this context, in order. - """ - self.type = context_type - self.start_token = start_token - self.end_token = None - - self.parent = None - self.children = [] - - if parent: - parent.AddChild(self) - - def __repr__(self): - """Returns a string representation of the context object.""" - stack = [] - context = self - while context: - stack.append(context.type) - context = context.parent - return 'Context(%s)' % ' > '.join(stack) - - def AddChild(self, child): - """Adds a child to this context and sets child's parent to this context. - - Args: - child: A child EcmaContext. The child's parent will be set to this - context. - """ - - child.parent = self - - self.children.append(child) - self.children.sort(EcmaContext._CompareContexts) - - def GetRoot(self): - """Get the root context that contains this context, if any.""" - context = self - while context: - if context.type is EcmaContext.ROOT: - return context - context = context.parent - - @staticmethod - def _CompareContexts(context1, context2): - """Sorts contexts 1 and 2 by start token document position.""" - return tokenutil.Compare(context1.start_token, context2.start_token) - - -class EcmaMetaData(object): - """Token metadata for EcmaScript languages. - - Attributes: - last_code: The last code token to appear before this one. - context: The context this token appears in. - operator_type: The operator type, will be one of the *_OPERATOR constants - defined below. - aliased_symbol: The full symbol being identified, as a string (e.g. an - 'XhrIo' alias for 'goog.net.XhrIo'). Only applicable to identifier - tokens. This is set in aliaspass.py and is a best guess. - is_alias_definition: True if the symbol is part of an alias definition. - If so, these symbols won't be counted towards goog.requires/provides. - """ - - UNARY_OPERATOR = 'unary' - - UNARY_POST_OPERATOR = 'unary_post' - - BINARY_OPERATOR = 'binary' - - TERNARY_OPERATOR = 'ternary' - - def __init__(self): - """Initializes a token metadata object.""" - self.last_code = None - self.context = None - self.operator_type = None - self.is_implied_semicolon = False - self.is_implied_block = False - self.is_implied_block_close = False - self.aliased_symbol = None - self.is_alias_definition = False - - def __repr__(self): - """Returns a string representation of the context object.""" - parts = ['%r' % self.context] - if self.operator_type: - parts.append('optype: %r' % self.operator_type) - if self.is_implied_semicolon: - parts.append('implied;') - if self.aliased_symbol: - parts.append('alias for: %s' % self.aliased_symbol) - return 'MetaData(%s)' % ', '.join(parts) - - def IsUnaryOperator(self): - return self.operator_type in (EcmaMetaData.UNARY_OPERATOR, - EcmaMetaData.UNARY_POST_OPERATOR) - - def IsUnaryPostOperator(self): - return self.operator_type == EcmaMetaData.UNARY_POST_OPERATOR - - -class EcmaMetaDataPass(object): - """A pass that iterates over all tokens and builds metadata about them.""" - - def __init__(self): - """Initialize the meta data pass object.""" - self.Reset() - - def Reset(self): - """Resets the metadata pass to prepare for the next file.""" - self._token = None - self._context = None - self._AddContext(EcmaContext.ROOT) - self._last_code = None - - def _CreateContext(self, context_type): - """Overridable by subclasses to create the appropriate context type.""" - return EcmaContext(context_type, self._token, self._context) - - def _CreateMetaData(self): - """Overridable by subclasses to create the appropriate metadata type.""" - return EcmaMetaData() - - def _AddContext(self, context_type): - """Adds a context of the given type to the context stack. - - Args: - context_type: The type of context to create - """ - self._context = self._CreateContext(context_type) - - def _PopContext(self): - """Moves up one level in the context stack. - - Returns: - The former context. - - Raises: - ParseError: If the root context is popped. - """ - top_context = self._context - top_context.end_token = self._token - self._context = top_context.parent - if self._context: - return top_context - else: - raise ParseError(self._token) - - def _PopContextType(self, *stop_types): - """Pops the context stack until a context of the given type is popped. - - Args: - *stop_types: The types of context to pop to - stops at the first match. - - Returns: - The context object of the given type that was popped. - """ - last = None - while not last or last.type not in stop_types: - last = self._PopContext() - return last - - def _EndStatement(self): - """Process the end of a statement.""" - self._PopContextType(EcmaContext.STATEMENT) - if self._context.type == EcmaContext.IMPLIED_BLOCK: - self._token.metadata.is_implied_block_close = True - self._PopContext() - - def _ProcessContext(self): - """Process the context at the current token. - - Returns: - The context that should be assigned to the current token, or None if - the current context after this method should be used. - - Raises: - ParseError: When the token appears in an invalid context. - """ - token = self._token - token_type = token.type - - if self._context.type in EcmaContext.BLOCK_TYPES: - # Whenever we're in a block, we add a statement context. We make an - # exception for switch statements since they can only contain case: and - # default: and therefore don't directly contain statements. - # The block we add here may be immediately removed in some cases, but - # that causes no harm. - parent = self._context.parent - if not parent or parent.type != EcmaContext.SWITCH: - self._AddContext(EcmaContext.STATEMENT) - - elif self._context.type == EcmaContext.ARRAY_LITERAL: - self._AddContext(EcmaContext.LITERAL_ELEMENT) - - if token_type == TokenType.START_PAREN: - if self._last_code and self._last_code.IsKeyword('for'): - # for loops contain multiple statements in the group unlike while, - # switch, if, etc. - self._AddContext(EcmaContext.FOR_GROUP_BLOCK) - else: - self._AddContext(EcmaContext.GROUP) - - elif token_type == TokenType.END_PAREN: - result = self._PopContextType(EcmaContext.GROUP, - EcmaContext.FOR_GROUP_BLOCK) - keyword_token = result.start_token.metadata.last_code - # keyword_token will not exist if the open paren is the first line of the - # file, for example if all code is wrapped in an immediately executed - # annonymous function. - if keyword_token and keyword_token.string in ('if', 'for', 'while'): - next_code = tokenutil.SearchExcept(token, TokenType.NON_CODE_TYPES) - if next_code.type != TokenType.START_BLOCK: - # Check for do-while. - is_do_while = False - pre_keyword_token = keyword_token.metadata.last_code - if (pre_keyword_token and - pre_keyword_token.type == TokenType.END_BLOCK): - start_block_token = pre_keyword_token.metadata.context.start_token - is_do_while = start_block_token.metadata.last_code.string == 'do' - - # If it's not do-while, it's an implied block. - if not is_do_while: - self._AddContext(EcmaContext.IMPLIED_BLOCK) - token.metadata.is_implied_block = True - - return result - - # else (not else if) with no open brace after it should be considered the - # start of an implied block, similar to the case with if, for, and while - # above. - elif (token_type == TokenType.KEYWORD and - token.string == 'else'): - next_code = tokenutil.SearchExcept(token, TokenType.NON_CODE_TYPES) - if (next_code.type != TokenType.START_BLOCK and - (next_code.type != TokenType.KEYWORD or next_code.string != 'if')): - self._AddContext(EcmaContext.IMPLIED_BLOCK) - token.metadata.is_implied_block = True - - elif token_type == TokenType.START_PARAMETERS: - self._AddContext(EcmaContext.PARAMETERS) - - elif token_type == TokenType.END_PARAMETERS: - return self._PopContextType(EcmaContext.PARAMETERS) - - elif token_type == TokenType.START_BRACKET: - if (self._last_code and - self._last_code.type in TokenType.EXPRESSION_ENDER_TYPES): - self._AddContext(EcmaContext.INDEX) - else: - self._AddContext(EcmaContext.ARRAY_LITERAL) - - elif token_type == TokenType.END_BRACKET: - return self._PopContextType(EcmaContext.INDEX, EcmaContext.ARRAY_LITERAL) - - elif token_type == TokenType.START_BLOCK: - if (self._last_code.type in (TokenType.END_PAREN, - TokenType.END_PARAMETERS) or - self._last_code.IsKeyword('else') or - self._last_code.IsKeyword('do') or - self._last_code.IsKeyword('try') or - self._last_code.IsKeyword('finally') or - (self._last_code.IsOperator(':') and - self._last_code.metadata.context.type == EcmaContext.CASE_BLOCK)): - # else, do, try, and finally all might have no () before {. - # Also, handle the bizzare syntax case 10: {...}. - self._AddContext(EcmaContext.BLOCK) - else: - self._AddContext(EcmaContext.OBJECT_LITERAL) - - elif token_type == TokenType.END_BLOCK: - context = self._PopContextType(EcmaContext.BLOCK, - EcmaContext.OBJECT_LITERAL) - if self._context.type == EcmaContext.SWITCH: - # The end of the block also means the end of the switch statement it - # applies to. - return self._PopContext() - return context - - elif token.IsKeyword('switch'): - self._AddContext(EcmaContext.SWITCH) - - elif (token_type == TokenType.KEYWORD and - token.string in ('case', 'default') and - self._context.type != EcmaContext.OBJECT_LITERAL): - # Pop up to but not including the switch block. - while self._context.parent.type != EcmaContext.SWITCH: - self._PopContext() - if self._context.parent is None: - raise ParseError(token, 'Encountered case/default statement ' - 'without switch statement') - - elif token.IsOperator('?'): - self._AddContext(EcmaContext.TERNARY_TRUE) - - elif token.IsOperator(':'): - if self._context.type == EcmaContext.OBJECT_LITERAL: - self._AddContext(EcmaContext.LITERAL_ELEMENT) - - elif self._context.type == EcmaContext.TERNARY_TRUE: - self._PopContext() - self._AddContext(EcmaContext.TERNARY_FALSE) - - # Handle nested ternary statements like: - # foo = bar ? baz ? 1 : 2 : 3 - # When we encounter the second ":" the context is - # ternary_false > ternary_true > statement > root - elif (self._context.type == EcmaContext.TERNARY_FALSE and - self._context.parent.type == EcmaContext.TERNARY_TRUE): - self._PopContext() # Leave current ternary false context. - self._PopContext() # Leave current parent ternary true - self._AddContext(EcmaContext.TERNARY_FALSE) - - elif self._context.parent.type == EcmaContext.SWITCH: - self._AddContext(EcmaContext.CASE_BLOCK) - - elif token.IsKeyword('var'): - self._AddContext(EcmaContext.VAR) - - elif token.IsOperator(','): - while self._context.type not in (EcmaContext.VAR, - EcmaContext.ARRAY_LITERAL, - EcmaContext.OBJECT_LITERAL, - EcmaContext.STATEMENT, - EcmaContext.PARAMETERS, - EcmaContext.GROUP): - self._PopContext() - - elif token_type == TokenType.SEMICOLON: - self._EndStatement() - - def Process(self, first_token): - """Processes the token stream starting with the given token.""" - self._token = first_token - while self._token: - self._ProcessToken() - - if self._token.IsCode(): - self._last_code = self._token - - self._token = self._token.next - - try: - self._PopContextType(self, EcmaContext.ROOT) - except ParseError: - # Ignore the "popped to root" error. - pass - - def _ProcessToken(self): - """Process the given token.""" - token = self._token - token.metadata = self._CreateMetaData() - context = (self._ProcessContext() or self._context) - token.metadata.context = context - token.metadata.last_code = self._last_code - - # Determine the operator type of the token, if applicable. - if token.type == TokenType.OPERATOR: - token.metadata.operator_type = self._GetOperatorType(token) - - # Determine if there is an implied semicolon after the token. - if token.type != TokenType.SEMICOLON: - next_code = tokenutil.SearchExcept(token, TokenType.NON_CODE_TYPES) - # A statement like if (x) does not need a semicolon after it - is_implied_block = self._context == EcmaContext.IMPLIED_BLOCK - is_last_code_in_line = token.IsCode() and ( - not next_code or next_code.line_number != token.line_number) - is_continued_operator = (token.type == TokenType.OPERATOR and - not token.metadata.IsUnaryPostOperator()) - is_continued_dot = token.string == '.' - next_code_is_operator = next_code and next_code.type == TokenType.OPERATOR - is_end_of_block = ( - token.type == TokenType.END_BLOCK and - token.metadata.context.type != EcmaContext.OBJECT_LITERAL) - is_multiline_string = token.type == TokenType.STRING_TEXT - is_continued_var_decl = (token.IsKeyword('var') and - next_code and - (next_code.type in [TokenType.IDENTIFIER, - TokenType.SIMPLE_LVALUE]) and - token.line_number < next_code.line_number) - next_code_is_block = next_code and next_code.type == TokenType.START_BLOCK - if (is_last_code_in_line and - self._StatementCouldEndInContext() and - not is_multiline_string and - not is_end_of_block and - not is_continued_var_decl and - not is_continued_operator and - not is_continued_dot and - not next_code_is_operator and - not is_implied_block and - not next_code_is_block): - token.metadata.is_implied_semicolon = True - self._EndStatement() - - def _StatementCouldEndInContext(self): - """Returns if the current statement (if any) may end in this context.""" - # In the basic statement or variable declaration context, statement can - # always end in this context. - if self._context.type in (EcmaContext.STATEMENT, EcmaContext.VAR): - return True - - # End of a ternary false branch inside a statement can also be the - # end of the statement, for example: - # var x = foo ? foo.bar() : null - # In this case the statement ends after the null, when the context stack - # looks like ternary_false > var > statement > root. - if (self._context.type == EcmaContext.TERNARY_FALSE and - self._context.parent.type in (EcmaContext.STATEMENT, EcmaContext.VAR)): - return True - - # In all other contexts like object and array literals, ternary true, etc. - # the statement can't yet end. - return False - - def _GetOperatorType(self, token): - """Returns the operator type of the given operator token. - - Args: - token: The token to get arity for. - - Returns: - The type of the operator. One of the *_OPERATOR constants defined in - EcmaMetaData. - """ - if token.string == '?': - return EcmaMetaData.TERNARY_OPERATOR - - if token.string in TokenType.UNARY_OPERATORS: - return EcmaMetaData.UNARY_OPERATOR - - last_code = token.metadata.last_code - if not last_code or last_code.type == TokenType.END_BLOCK: - return EcmaMetaData.UNARY_OPERATOR - - if (token.string in TokenType.UNARY_POST_OPERATORS and - last_code.type in TokenType.EXPRESSION_ENDER_TYPES): - return EcmaMetaData.UNARY_POST_OPERATOR - - if (token.string in TokenType.UNARY_OK_OPERATORS and - last_code.type not in TokenType.EXPRESSION_ENDER_TYPES and - last_code.string not in TokenType.UNARY_POST_OPERATORS): - return EcmaMetaData.UNARY_OPERATOR - - return EcmaMetaData.BINARY_OPERATOR diff --git a/tools/closure_linter/build/lib/closure_linter/error_check.py b/tools/closure_linter/build/lib/closure_linter/error_check.py deleted file mode 100644 index 8d657fe9174fff..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/error_check.py +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2011 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - - -"""Specific JSLint errors checker.""" - - - -import gflags as flags - -FLAGS = flags.FLAGS - - -class Rule(object): - """Different rules to check.""" - - # Documentations for specific rules goes in flag definition. - BLANK_LINES_AT_TOP_LEVEL = 'blank_lines_at_top_level' - INDENTATION = 'indentation' - WELL_FORMED_AUTHOR = 'well_formed_author' - NO_BRACES_AROUND_INHERIT_DOC = 'no_braces_around_inherit_doc' - BRACES_AROUND_TYPE = 'braces_around_type' - OPTIONAL_TYPE_MARKER = 'optional_type_marker' - VARIABLE_ARG_MARKER = 'variable_arg_marker' - UNUSED_PRIVATE_MEMBERS = 'unused_private_members' - UNUSED_LOCAL_VARIABLES = 'unused_local_variables' - - # Rule to raise all known errors. - ALL = 'all' - - # All rules that are to be checked when using the strict flag. E.g. the rules - # that are specific to the stricter Closure style. - CLOSURE_RULES = frozenset([BLANK_LINES_AT_TOP_LEVEL, - INDENTATION, - WELL_FORMED_AUTHOR, - NO_BRACES_AROUND_INHERIT_DOC, - BRACES_AROUND_TYPE, - OPTIONAL_TYPE_MARKER, - VARIABLE_ARG_MARKER]) - - -flags.DEFINE_boolean('strict', False, - 'Whether to validate against the stricter Closure style. ' - 'This includes ' + (', '.join(Rule.CLOSURE_RULES)) + '.') -flags.DEFINE_multistring('jslint_error', [], - 'List of specific lint errors to check. Here is a list' - ' of accepted values:\n' - ' - ' + Rule.ALL + ': enables all following errors.\n' - ' - ' + Rule.BLANK_LINES_AT_TOP_LEVEL + ': validates' - 'number of blank lines between blocks at top level.\n' - ' - ' + Rule.INDENTATION + ': checks correct ' - 'indentation of code.\n' - ' - ' + Rule.WELL_FORMED_AUTHOR + ': validates the ' - '@author JsDoc tags.\n' - ' - ' + Rule.NO_BRACES_AROUND_INHERIT_DOC + ': ' - 'forbids braces around @inheritdoc JsDoc tags.\n' - ' - ' + Rule.BRACES_AROUND_TYPE + ': enforces braces ' - 'around types in JsDoc tags.\n' - ' - ' + Rule.OPTIONAL_TYPE_MARKER + ': checks correct ' - 'use of optional marker = in param types.\n' - ' - ' + Rule.UNUSED_PRIVATE_MEMBERS + ': checks for ' - 'unused private variables.\n' - ' - ' + Rule.UNUSED_LOCAL_VARIABLES + ': checks for ' - 'unused local variables.\n') - - -def ShouldCheck(rule): - """Returns whether the optional rule should be checked. - - Computes different flags (strict, jslint_error, jslint_noerror) to find out if - this specific rule should be checked. - - Args: - rule: Name of the rule (see Rule). - - Returns: - True if the rule should be checked according to the flags, otherwise False. - """ - if rule in FLAGS.jslint_error or Rule.ALL in FLAGS.jslint_error: - return True - # Checks strict rules. - return FLAGS.strict and rule in Rule.CLOSURE_RULES diff --git a/tools/closure_linter/build/lib/closure_linter/error_fixer.py b/tools/closure_linter/build/lib/closure_linter/error_fixer.py deleted file mode 100644 index 88f9c720ab3517..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/error_fixer.py +++ /dev/null @@ -1,618 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Main class responsible for automatically fixing simple style violations.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = '[email protected] (Robert Walker)' - -import re - -import gflags as flags -from closure_linter import errors -from closure_linter import javascriptstatetracker -from closure_linter import javascripttokens -from closure_linter import requireprovidesorter -from closure_linter import tokenutil -from closure_linter.common import errorhandler - -# Shorthand -Token = javascripttokens.JavaScriptToken -Type = javascripttokens.JavaScriptTokenType - -END_OF_FLAG_TYPE = re.compile(r'(}?\s*)$') - -# Regex to represent common mistake inverting author name and email as -# @author User Name (user@company) -INVERTED_AUTHOR_SPEC = re.compile(r'(?P\s*)' - r'(?P[^(]+)' - r'(?P\s+)' - r'\(' - r'(?P[^\s]+@[^)\s]+)' - r'\)' - r'(?P